//add by yim.hu FUN-BK-0009 申明4个变量 start
price1_xiaoji = 0;
price2_xiaoji = 0;
ewaicanju ='无';//额外餐具默认为空格
ewaishengri = '无';//额外生日
//add by yim.hu FUN-BK-0009  申明4个变量 end	
if(typeof bill == "undefined") {
    var bill = {};
}


bill.define = {
    d_send: '请先选择并确认收货信息',
    s_pay: '请先选择并确认配送方式',
    n_send: '当前收货地址的配送方法没有找到，请选择其他地址',
    n_pay: '当前配送方式的支付方式没有找到，请选择其他配送方式'
};

bill.global = {

    general_goods : { },

    isDeliveryTime : 0,

    up_freight: 0,

    total_receivable_money: 0,

    card_is_invoice: 1,  //特殊卡是否可以开发票

    //唱单
    submit: {

        open: function() {

            var msg = '';
            //add by yim.hu 20141113 判断切分是否为数字 --start  
            //这里判断切分
            var l = $('.syncopate').length
            var i;
            for(i=0; i<l; i++){
            	if(isNaN($('.syncopate').eq(i).val()) == true){
            		msg+='切分必须为数字<br />';
            		break;
            	}
            	
            }
            //add by yim.hu 20141113 判断切分是否为数字 --end  
           
            if (Object.keys(bill.generalGoods.general_data).length == 0 && $.isEmptyObject(bill.paying_agent.paying_agent_array)) {
                msg += '请先添加商品<br/>';
            }

            //检查配送时间



            //add by 20141111 sunqiang FUN-BK-0021 订单为已下车状态可修改订单 start
            if(bill.args.bill_status !=5 && bill.args.bill_status !=6 )
            {
                if(!bill.global.isDeliveryTime){
                    msg += '请确定配送时间<br/>';
                    $("html,body").animate({scrollTop:$("#send_time_box").offset().top-200},1000)
                }
            }

//            if(!bill.global.isDeliveryTime){
//                msg += '请确定配送时间<br/>';
//                $("html,body").animate({scrollTop:$("#send_time_box").offset().top-200},1000)
//            }
            //add by 20141111 sunqiang FUN-BK-0021 订单为已下车状态可修改订单 end




            var billCity = $("#billCity").val(),
                urgent = $("#urgent").val(),
                billPlatform = $('#billPlatform').val(),
                billChannel = bill.args.source,
                billType = $('#billType').val(),
                billPromotion = $("#billPromotion").val();
                operateType = $("#operateType").val();
            var numPeo= $("#numPeo").val();//试吃人数
            var pay_info = $('label[for="pay-square-radio-' + bill.args.buy_log.payTypeID + '"]').text();
            var invoice_info = $('label[for="invoice-square-radio-' + bill.args.buy_log.invoiceID + '"]').text();
             //试吃订单--试吃人数
            if(billType==9){
                pay_info=1;
                if(E.empty(numPeo))
                msg += '请输入试吃人数<br/>';
            }
            //add by 20141105 allen.qiang FUN-AC-0013-销售BD双11活动 start
            var bill_remark=$("#bill_remark").val();//内部备注
            //双11送礼包活动渠道仅限上海 且 内部备注不能为空
            if(billPromotion==368 || billPromotion==369 || billPromotion==370){
                if(billCity==641)
                    msg += '双11送礼包活动仅限上海<br/>';
                else if(E.empty(bill_remark))
                    msg += '请输入内部备注<br/>';
            }
            //add by 20141105 allen.qiang FUN-AC-0013-销售BD双11活动 end
            if(E.empty(billCity)){
                msg += '请选择城市<br/>';
            }

            if(E.empty(billPlatform)){
                msg += '请选择订单平台<br/>';
            }

            if(E.empty(billType)){
                msg += '请选择订单类型<br/>';
            }

            if(E.empty(pay_info)){
                msg += '请选择支付方式<br/>';
            }

            if (bill.args.buy_log.pay_type == 1 && E.isEmpty(bill.args.buy_log.pay_type)) {
                msg += '请选择付款方式<br>';
            }

            if (bill.card.to_activate_num > 0) {
                msg += '有未激活的现金卡，请激活或取消<br>';
            }

            if(bill.args.total.total_receivable_money > 0 && bill.global.card_is_invoice == 1 && E.empty(invoice_info)){
                msg += '请选择发票';
            }

            if(!E.empty(msg)){
                E.alert(msg);
                return false;
            }
            //add by loreta.cheng 2015-06-12 添加试吃订单提交的时候弹出该会员的地址列表，选中的突出显示 start
            if(billType==9 && operateType==1){
              
              E.ajax_post({
                url: "/invokingAjax-comm/bill/checkout.ajax?operFlg=1",
                data: {
                    buy_log: bill.args.buy_log,
                    source: bill.args.source,
                    billType: bill.args.billType,
                    orders_code:bill.args.orders_code
                },
                call: function(o){
                    var ds = bill.define;
                    if (o.code == 200) {
                     if (!o.data.deliver) { //没有收货地址
                        bill.send.create.error(ds.d_send);
                        bill.pay.create.error(ds.s_pay);
                     }else{
                     var showAddressList='';
                     showAddressList += '<div class="panel panel-default">';
                     showAddressList += '<div class="panel-heading">地址列表</div>';
                     showAddressList += '<div class="panel-body form-horizontal">';
                     $.each(o.data.deliver, function(k, v){
                     
                     if (bill.deliver.d_data[v.deliverID]) {
                      if (v.deliverID == bill.args.buy_log.deliverID) {
                            showAddressList += '<li class="list-group-item" >';
                            showAddressList += '<label style="font-weight:bold;">';
                        } else {
                            showAddressList += '<li class="list-group-item">';
                            showAddressList += '<label style="font-weight:normal;">';
                        }

                        
                        showAddressList += v.custName + '，' ;
                        if (v.mobile) {
                            showAddressList += v.provinceName + v.cityName + v.countyName + ' ' + v.address + '，' + v.mobile;
                            if(v.type == 2){
                                showAddressList += '<span style="color: red;">&nbsp;&nbsp;自提站点</span>';
                            }
                        } else {
                            showAddressList += v.provinceName + v.cityName + v.countyName + ' ' + v.address + '，' + v.phone;
                            if(v.type == 2){
                                showAddressList += '<span style="color: red;">&nbsp;&nbsp;自提站点</span>';
                            }
                        }
                        showAddressList += '</label>';
                        showAddressList += '</li>';
                     }else{
                        if(bill.args.bill_status != 5 && bill.args.bill_status != 6){

                           if (v.deliverID == bill.args.buy_log.deliverID) {
                                showAddressList += '<li class="list-group-item">';
                                showAddressList += '<label style="font-weight:bold;">';
                            } else {
                                showAddressList += '<li class="list-group-item">';
                                showAddressList += '<label style="font-weight:normal;">';
                            }

                            
                            showAddressList += v.custName + '，' ;

                            if (v.mobile) {
                                showAddressList += v.provinceName + v.cityName + v.countyName + ' ' + v.address + '，' + v.mobile;
                            } else {
                                showAddressList += v.provinceName + v.cityName + v.countyName + ' ' + v.address + '，' + v.phone;
                            }

                            if(v.type == 2){
                                showAddressList += '<span style="color: red;">&nbsp;&nbsp;自提站点</span>';
                            }

                            showAddressList += '</label>';
                            showAddressList += '</li>';
                        }else{
                            if (v.deliverID == bill.args.buy_log.deliverID) {
                                showAddressList += '<li class="list-group-item" >';
                                showAddressList +=  '<label style="font-weight:bold;">';
                                }else{
                                showAddressList += '<li class="list-group-item">';
                                showAddressList +=  '<label style="font-weight:normal;">';
                                }
               
                                showAddressList += v.custName + '，' ;
                                if (v.mobile) {
                                    showAddressList += v.provinceName + v.cityName + v.countyName + ' ' + v.address + '，' + v.mobile;
                                } else {
                                    showAddressList += v.provinceName + v.cityName + v.countyName + ' ' + v.address + '，' + v.phone;
                                }
                                if(v.type == 2){
                                    showAddressList += '<span style="color: red;">&nbsp;&nbsp;自提站点</span>';
                                }
                                showAddressList += '</label>';
                                showAddressList += '</li>';                            
                            }

                        }

                      });
                      showAddressList +='</div></div>';
					  E.popup.open({
                        title: '核对地址',
                        content: showAddressList,
                        css: 'width: 700px',
                        btnName: '确定',
                        btnCall: 'bill.global.submit.showBill();'});//点击确定后执行的方法
                    }
				  }else{
                     E.alert(o.message); 
                  }
				 }
                });
            }else{
              bill.global.submit.showBill();  
            }
            //add by loreta.cheng 2015-06-12 添加试吃订单提交的时候弹出该会员的地址列表，选中的突出显示 end

            
            //add by 20141126 allen.qiang FUN-AC-0022-拿破仑莓恋预售 end
            //del by 20141201 allen.qiang FUN-AC-0022-拿破仑莓恋预售 start
//            E.popup.open({
//                title: '核对订单',
//                content: html,
//                css: 'width: 700px',
//                btnName: bill.args.bill_no ? '修改订单' : '新增订单',
//                btnCall: 'bill.global.submit.start();'
//            });
            //del by 20141201 allen.qiang FUN-AC-0022-拿破仑莓恋预售 end

        },
        //showAddressList:function(){
        //   bill.global.submit.showBill(); 
       //},

        showBill: function()
        {
            E.popup.close();
            var fittings_data = { };
            var html = '<div class="panel panel-default">';
            html += '<div class="panel-heading">订单商品</div>';
            html += '<table class="table">';
            html += '<thead>';
            html += '<tr>';
            html += '<th>商品名称</th>';
            html += '<th style="text-align: center;">规格</th>';
            html += '<th style="text-align: center;">数量</th>';
            html += '<th style="text-align: center;">金额</th>';
            html += '<th style="text-align: center;">生日牌</th>';
            html += '</tr>';
            html += '</thead>';
            html += '<tbody>';
            $.each(bill.generalGoods.general_data, function(k, v) {

                //循环计算配件列表
                if (v.fittings) {
                    $.each(v.fittings,function( ke,va ){
                        if(va){
                            var fitID = va.fitID;
                            if(va.price == null){
                                va.price = 0.00;
                            }
                            if(fittings_data[fitID]){
                                fittings_data[fitID].buyNum += va.buyNum;
                                fittings_data[fitID].buyMoney += parseFloat(va.price*va.buyNum);
                                fittings_data[fitID].buyMoney = fittings_data[fitID].buyMoney;
                            }else{

                                fittings_data[fitID] = {
                                    fitName: va.fitName,
                                    fitUnit: va.fitUnit,
                                    unitName: va.unitName,
                                    quantity: va.quantity,
                                    forsale: va.forsale,
                                    price: va.price,
                                    buyNum: parseInt(va.buyNum),
                                    buyMoney: va.price*va.buyNum
                                }
                            }
                        }
                    });
                }

                var birthcard = $("#goods_"+k).find(".birthcard").val();

                html += '<tr>';
                html += '<td style="height:35px;line-height:35px;">' + v.goodsName + '</td>';
                html += '<td style="text-align: center;line-height:35px;">' + v.spec + '</td>';
                html += '<td style="text-align: center;line-height:35px;">' + v.goods_amount + '</td>';
                html += '<td style="text-align: center;line-height:35px;">' + parseFloat(v.price).toFixed(2) + '</td>';
                html += '<td style="text-align: center;line-height:35px;">'+ birthcard +'</td>';
                html += '</tr>';

                if(v.fittings){
                    var count = 0;
                    html += '<tr><td colspan="5"><div class="panel panel-default"><table class="table table-striped table-hover">';
                    $.each(v.fittings,function(key,val){
                        if(val){
                            if(count == 0){
                                html += '<tr>';
                                html += '<th width="40%">名称</th>';
                                html += '<th width="20%" style="text-align: center;">赠送数量</th>';
                                html += '<th width="20%" style="text-align: center;">额外购买数量</th>';
                                html += '<th width="20%" style="text-align: center;">额外购买金额</th>';
                                html += '</tr>';
                            }

                            var price = parseFloat(val.buyNum*val.price).toFixed(2);

                            if(val.fitName == '额外餐具'){
                                ewaicanju = key
                                //如果是修改订单
                                if(GetQueryString('operFlg')==1){
                                    //假如有购买金额
                                    if(val.buyMoney>0){
                                        var price = parseFloat(Math.ceil(val.buyNum*val.buyMoney)).toFixed(2);
                                    }else{
                                        var price = parseFloat(val.buyNum*val.price).toFixed(2);
                                    }
                                }else{
                                    if(price1_xiaoji==0){
                                        
                                        var price = parseFloat(val.buyNum*val.price).toFixed(2);
                                    }else{
                                        var price = price1_xiaoji.toFixed(2);
                                    }                                   
                                }

                                
                            }else if(val.fitName == '额外生日蜡烛'){
                                ewaishengri = key
                                //如果是修改订单
                                if(GetQueryString('operFlg')==1){
                                    //假如有购买金额
                                    if(val.buyMoney>0){
                                        var price = parseFloat(Math.ceil(val.buyNum*val.buyMoney)).toFixed(2);
                                    }else{
                                        var price = parseFloat(val.buyNum*val.price).toFixed(2);
                                    }
                                }else{
                                    if(price2_xiaoji==0){
                                        
                                        var price = parseFloat(val.buyNum*val.price).toFixed(2);
                                    }else{
                                        var price = price2_xiaoji.toFixed(2);
                                    }                                   
                                }                               
                            }else{
                                var price = parseFloat(val.buyNum*val.price).toFixed(2);
                            }                            
                            html += '<tr>';
                            html += '<td>'+ val.fitName +'(/'+ val.unitName +')</td>';
                            html += '<td style="text-align: center;">'+ val.quantity +'</td>';
                            html += '<td style="text-align: center;">'+ val.buyNum +'</td>';
                            html += '<td style="text-align: center;">'+ price +'</td>';
                            html += '</tr>';

                            count++;
                        }

                    });
                    html += '</table></div></td></tr>';

                }

            });
            html += '</tbody>';
            html += '</table>';
            html += '</div>';

            html += '<div class="panel panel-default">';
            html += '<div class="panel-heading">订单信息</div>';
            html += '<div class="panel-body form-horizontal">';

            var deliver_info = $('label[for="deliver-square-radio-' + bill.args.buy_log.deliverID + '"]').text();
            html += '<div class="form-group">';
            html += '<label class="col-sm-2 control-label">收货地址</label>';
            html += '<div class="col-sm-10">';
            html += '<p class="form-control-static">' + deliver_info + '</p>';
            html += '</div>';
            html += '</div>';

            var send_info = $('label[for="send-square-radio-' + bill.args.buy_log.send_region_id + '"]').text();
            html += '<div class="form-group">';
            html += '<label class="col-sm-2 control-label">配送方式</label>';
            html += '<div class="col-sm-10">';
            html += '<p class="form-control-static">' + send_info + '</p>';
            html += '</div>';
            html += '</div>';

            var send_date = $('#send_date').val();
            html += '<div class="form-group">';
            html += '<label class="col-sm-2 control-label">配送日期</label>';
            html += '<div class="col-sm-10">';
            html += '<p class="form-control-static">' + send_date + '</p>';
            html += '</div>';
            html += '</div>';
            //mod yim.hu 20141128 FUN-BK-0036 新增订单爆单提示 --start
            //var send_start_time = $("#start_time").val();
            var send_start_time = $("#hidden_start_time").val();
            //mod yim.hu 20141128 FUN-BK-0036 新增订单爆单提示 --end
            //add yim.hu 20141128 FUN-BK-0036 新增订单爆单提示 --start
            //如果有逗号就删除
            if(send_start_time.indexOf(',')>0){             
                send_start_time = send_start_time.substring(0,8);
            }   
            //add yim.hu 20141128 FUN-BK-0036 新增订单爆单提示 --end
            var send_end_time = $("#hidden_end_time").val();
            html += '<div class="form-group">';
            html += '<label class="col-sm-2 control-label">配送时间</label>';
            html += '<div class="col-sm-10">';
            //add yim.hu 20141128 FUN-BK-0036 新增订单爆单提示 --start
                //html += '<p class="form-control-static">开始配送时间：' + send_start_time + '&nbsp;&nbsp;时间段结束时间：'+ send_end_time +'</p>';
            html += '<p class="form-control-static">开始配送时间：' + send_start_time + '&nbsp;&nbsp;时间段结束时间：'+ send_end_time +'</p>';

            //add yim.hu 20141128 FUN-BK-0036 新增订单爆单提示 --end
            html += '</div>';
            html += '</div>';

            var pay_info = $('label[for="pay-square-radio-' + bill.args.buy_log.payTypeID + '"]').text();
            html += '<div class="form-group">';
            html += '<label class="col-sm-2 control-label">支付方式</label>';
            html += '<div class="col-sm-10">';
            html += '<p class="form-control-static">' + pay_info + '</p>';
            html += '</div>';
            html += '</div>';

            if (bill.args.total.total_receivable_money > 0 && bill.global.card_is_invoice == 1) {
                var invoice_info = $('label[for="invoice-square-radio-' + bill.args.buy_log.invoiceID + '"]').text();
            } else {
                var invoice_info = '不开发票';
            }
            html += '<div class="form-group">';
            html += '<label class="col-sm-2 control-label">发票</label>';
            html += '<div class="col-sm-10">';
            html += '<p class="form-control-static">' + invoice_info + '</p>';
            html += '</div>';
            html += '</div>';

            var invoice_content = $('#invoice_content option:selected').text();
            html += '<div class="form-group">';
            html += '<label class="col-sm-2 control-label">发票内容</label>';
            html += '<div class="col-sm-10">';
            html += '<p class="form-control-static">' + invoice_content + '</p>';
            html += '</div>';
            html += '</div>';

            //代付订单
            var paying_agent_tbody_tr_obj = $('#paying_agent_table tbody').find("tr");
            if(paying_agent_tbody_tr_obj.length > 0){

                html += '<div class="form-group">';
                html += '<label class="col-sm-2 control-label">代付订单</label>';
                html += '<div class="col-sm-10">';

                for(var i = 0; i < paying_agent_tbody_tr_obj.length; i++){
                    var bill_code = paying_agent_tbody_tr_obj.eq(i).find('td').eq(0).text();
                    html += '<p class="form-control-static">' + bill_code + '</p>';
                }

                html += '</div>';
                html += '</div>';
            }

            //现金卡
            if(!$.isEmptyObject(bill.card.card_array)){
                html += '<div class="form-group">';
                html += '<label class="col-sm-2 control-label">使用现金卡</label>';
                html += '<div class="col-sm-10">';
                $.each(bill.card.card_array,function( k, v ){
                    html += '<p class="form-control-static">' + v + '</p>';
                });
                html += '</div>';
                html += '</div>';
            }

            //优惠券
            if(!$.isEmptyObject(bill.coupon.use_coupon_array)){
                html += '<div class="form-group">';
                html += '<label class="col-sm-2 control-label">使用优惠券</label>';
                html += '<div class="col-sm-10">';

                $.each(bill.coupon.use_coupon_array,function(k, v){
                    html += '<p class="form-control-static">' + v + '</p>';
                })

                html += '</div>';
                html += '</div>';
            }

            //余额
            var balance = $("#balance_number").val();
            if(!E.empty(balance)){
                html += '<div class="form-group">';
                html += '<label class="col-sm-2 control-label">使用余额</label>';
                html += '<div class="col-sm-10">';
                html += '<p class="form-control-static">' + balance + '</p>';
                html += '</div>';
                html += '</div>';
            }

            html += '<div class="form-group">';
            html += '<label class="col-sm-2 control-label">订单金额</label>';
            html += '<div class="col-sm-10">';
            html += '<p class="form-control-static"><b class="red">' + bill.args.total.bill_money.toFixed(2) + '</b></p>';
            html += '</div>';
            html += '</div>';

            html += '<div class="form-group">';
            html += '<label class="col-sm-2 control-label">运费</label>';
            html += '<div class="col-sm-10">';
            html += '<p class="form-control-static"><b class="red">' + parseFloat(bill.args.total.deliver_feePaid).toFixed(2) + '</b></p>';
            html += '</div>';
            html += '</div>';

            html += '<div class="form-group">';
            html += '<label class="col-sm-2 control-label">订单立减</label>';
            html += '<div class="col-sm-10">';
            html += '<p class="form-control-static"><b class="red">' + bill.args.total.total_subtract_money.toFixed(2) + '</b></p>';
            html += '</div>';
            html += '</div>';

            html += '<div class="form-group">';
            html += '<label class="col-sm-2 control-label">应收金额</label>';
            html += '<div class="col-sm-10">';
            html += '<p class="form-control-static"><b class="red">' + bill.args.total.total_receivable_money.toFixed(2) + '</b></p>';
            html += '</div>';
            html += '</div>';

            html += '<div class="form-group">';
            html += '<label class="col-sm-2 control-label">赠送积分</label>';
            html += '<div class="col-sm-10">';
            html += '<p class="form-control-static"><b class="red">' + bill.args.total.total_points.toFixed(2) + '</b></p>';
            html += '</div>';
            html += '</div>';

            html += '</div>';
            html += '</div>';
            //add by 20141126 allen.qiang FUN-AC-0022-拿破仑莓恋预售 start
            var numcode=0;
            E.ajax_post({
                action:'checkout',
                operFlg:26,
                data: {
                    goods:bill.generalGoods.general_data,
                    sendDate:send_date
                },
                call: function(o){

                    if(o.code==200){
                        var textVal="核对订单";
                    }else{
                        var textVal="核对订单 <span style='color:red;padding-left: 50px;'>所选配送日期"+ o.message+"商品已爆单</span>";
                    }
                    E.popup.open({
                        title: textVal,
                        content: html,
                        css: 'width: 700px',
                        btnName: bill.args.bill_no ? '修改订单' : '新增订单',
                        btnCall: 'bill.global.submit.start(0);'
                    });

                }
            });

        },

        start: function(nocheck_val) {


            var billCity = $("#billCity").val(),
                urgent = $("#urgent").val(),
                billPlatform = $('#billPlatform').val(),
                billChannel = '',
                properties = $('#properties').val(),
                billType = $('#billType').val();
            var numPeo= $("#numPeo").val();//试吃订单人数

            switch (bill.args.source){

                case 'web':
                    billChannel = 1;
                    break;

                case 'wap':
                    billChannel = 2;
                    break;

                case 'weixin':
                    billChannel = 3;
                    break;

                case 'app':
                    billChannel = 4;
                    break;

                case 'backend':
                    billChannel = 6;
                    break;

            }

            bill.global.general_goods = { };
            //获取普通商品的信息
            $.each($("#general_line tr"),function(k,v){

                var key = $("#general_line tr").eq(k).attr('id').replace('goods_','');

                bill.global.general_goods[key] = {
                    birthcard : $("#general_line tr").eq(k).find(".birthcard").val(),
                    syncopate : $("#general_line tr").eq(k).find("input[name='syncopate']").val(),
                    productRemark : $("#general_line tr").eq(k).find(".productRemark").val()
                }
            });

            if (bill.args.bill_no) {
                E.loadding.open('正在修改订单，请稍候...');
            } else{
            	E.loadding.open('正在新增订单，请稍候...');
            }

            $(".btn-success").hide();
            E.ajax_post({
                url: '/invokingAjax-backend/bill/bill.ajax?operFlg=1',
                data: {
                    invoice_content_id: $('#invoice_content').val(),
                    invoice_content: $("#invoice_content option:selected").text(),
                    code: bill.args.code,
                    orders_code: bill.args.orders_code,
                    pcustID: bill.args.pcustID,
                    bill_no: bill.args.bill_no,
                    remark: E.trim($('#remark').val()),
                    urgent:urgent,
                    billPlatform: billPlatform,
                    properties: properties,
                    billChannel: billChannel,
                    billType: billType,
                    bill_remark: $.trim($("#bill_remark").val()),       //内部留言
                    general_goods:bill.global.general_goods,
                    numPeo:numPeo,     //试吃订单--试吃人数
                    nocheck:nocheck_val
                },
                call: 'bill.global.submit.result'
            });
        },
        result_check: function (){
        	E.loadding.open('正在新增订单，请稍候...');
            var billCity = $("#billCity").val(),
            urgent = $("#urgent").val(),
            billPlatform = $('#billPlatform').val(),
            billChannel = '',
            properties = $('#properties').val(),
            billType = $('#billType').val();
	        var numPeo= $("#numPeo").val();//试吃订单人数
	
	        switch (bill.args.source){
	
	            case 'web':
	                billChannel = 1;
	                break;
	
	            case 'wap':
	                billChannel = 2;
	                break;
	
	            case 'weixin':
	                billChannel = 3;
	                break;
	
	            case 'app':
	                billChannel = 4;
	                break;
	
	            case 'backend':
	                billChannel = 6;
	                break;
	
	        }
	
	        bill.global.general_goods = { };
	        //获取普通商品的信息
	        $.each($("#general_line tr"),function(k,v){
	
	            var key = $("#general_line tr").eq(k).attr('id').replace('goods_','');
	
	            bill.global.general_goods[key] = {
	                birthcard : $("#general_line tr").eq(k).find(".birthcard").val(),
	                syncopate : $("#general_line tr").eq(k).find("input[name='syncopate']").val(),
	                productRemark : $("#general_line tr").eq(k).find(".productRemark").val()
	            }
	        });   	
            E.ajax_post({
                url: '/invokingAjax-backend/bill/bill.ajax?operFlg=1',
                data: {
                    invoice_content_id: $('#invoice_content').val(),
                    invoice_content: $("#invoice_content option:selected").text(),
                    code: bill.args.code,
                    orders_code: bill.args.orders_code,
                    pcustID: bill.args.pcustID,
                    bill_no: bill.args.bill_no,
                    remark: E.trim($('#remark').val()),
                    urgent:urgent,
                    billPlatform: billPlatform,
                    properties: properties,
                    billChannel: billChannel,
                    billType: billType,
                    bill_remark: $.trim($("#bill_remark").val()),       //内部留言
                    general_goods:bill.global.general_goods,
                    numPeo:numPeo     //试吃订单--试吃人数
                },
                call: 'bill.global.submit.result'
            });         	        	
        	
        },
        //add yim.hu 20141401 FUN-BK-0033 新增订单前CHECK --end
        result: function( o ){ 

            E.loadding.close();

            if (o.code == 200) {
                if (bill.args.bill_no) {
                    E.alert("订单修改成功", 3, 'E.closeWindows');
                }
                else {
                    E.alert("订单新增成功<br>订单编号：" + o.data.bill_code, 3, 'E.closeWindows');
                }
            }
            else if(o.code == 505)
            {
                E.confirm(o.message + '<br /> 确定提交吗?','bill.global.submit.start(1)');
            }
            else {
                E.alert(o.message);
            }

        }

    },

    /**
     * 加载会员收货、配送方式、支付方式、发票等信息
     */
    load: {

        start: function() {
            E.ajax_post({
                url: "/invokingAjax-comm/bill/checkout.ajax?operFlg=1",
                data: {
                    buy_log: bill.args.buy_log,
                    source: bill.args.source,
                    billType: bill.args.billType,
                    orders_code:bill.args.orders_code
                },
                call: "bill.global.load.result"
            });
        },

        result: function( o ) {

            var d = bill.define;

            if (o.code == 200) {

                var log = o.data.log;

                if (!o.data.deliver) { //没有收货地址

                    bill.send.create.error(d.d_send);
                    bill.pay.create.error(d.s_pay);

                } else {

                    //收货地址ID
                    bill.args.buy_log.deliverID = log.deliverID;

                    //显示地址
                    $.each(o.data.deliver, function(k, v) {
                        bill.deliver.createAddressList( v );
                    });

                    if (o.data.distribution) {

                    	$('#distribution').html(o.data.distribution.distribution_name);
                        //add yim.hu 20141129 FUN-BK-0036 新增订单爆单提示 --start
                    	E.loadding.open('正在努力加载中...');
                    	//给一个配送站ID方便查询数据
                        $('#distribution').attr('key',o.data.distribution.distribution_id);
                        //这里开始判断初始的时间
                        var start_date = $('#send_date').val();
                        var distribution_id = o.data.distribution.distribution_id;
            			$.ajax({
            	            url: "/invokingAjax-shop/default/checkout.ajax?operFlg=24",
            	            data: {
            	            	distribution_id : o.data.distribution.distribution_id,
            	            	send_date	:  $('#send_date').val()

            	            },
            	            type: "POST",
            	            success: function(data){
            	            	$('#tishi_baodan').hide();
            	            	E.loadding.close();
            	            	var data = eval('(' + data + ')');
                                var time_str = $('#start_time').val().split(',')[0];

                                //先清空开始时间
                                $('#start_time').html('');
                                $('#start_time').append("<option value=''>请选择开始时间</option>")
                                $.each(data,function(i,key){
                                    var isselected = "";
                                    if(key.itemName ==time_str)
                                    {
                                        isselected = "selected";
                                    }

                                    if(key.h==1){
                                        if($('#send_time_text').is(":hidden")==false){
                                            $('#tishi_baodan').show();
                                        }
                                        $('#start_time').append("<option value='"+key.itemName+",1' " +isselected + " >"+key.itemName+" (爆单)</option>");
                                    }else{
                                        $('#start_time').append("<option value='"+key.itemName+"' " +isselected + " >"+key.itemName+"</option>");

                                    }
                                });

            	            }            
            	        });  
                        //add yim.hu 20141126 FUN-BK-0036 新增订单爆单提示 --end
                    } else {
                        $('#distribution').html('未匹配到配送站');
                    }

                    if (!o.data.send) { //没有配送方式

                        bill.send.create.error(d.n_send);
                        bill.pay.create.error(d.s_pay);

                    } else {

                        //配送区域ID
                        bill.args.buy_log.send_region_id = log.send_region_id;

                        if ($(o.data.send).length <= 1) {
                            $("#send_box").hide();
                        } else {
                            $("#send_box").show();
                        }
                        bill.send.create.list( o.data.send );


                        if (!o.data.pay || o.data.pay.length == 0) { //没有支付方式

                            bill.pay.create.error( d.n_pay );

                        } else {

                            //支付方式ID和支付类型
                            bill.args.buy_log.payTypeID = log.payTypeID;
                            bill.args.buy_log.pay_type = log.pay_type;
                            bill.args.buy_log.payment_method_id = log.payment_method_id;

                            //显示支付方式
                            bill.pay.create.list( o.data.pay );

                        }
                    }
                }

                /**
                 * =====================
                 * 发票信息
                 * =====================
                 */
                if (o.data.invoice) {

                    bill.args.buy_log.invoiceID = log.invoiceID;
                    $.each(o.data.invoice, function(k, v) {
                        bill.invoice.createInvoiceList( v );
                    });

                }
                /**
                 * =====================
                 * 发票信息
                 * =====================
                 */

                bill.global.total();

            } else {

                E.alert(o.message);

            }

        }

    },

    //检查商品促销、订单促销、计算订单相关金额
    total: function() {

        E.ajax_post({
            url: '/invokingAjax-comm/bill/checkout.ajax?operFlg=9',
            data: {
                buy_log: bill.args.buy_log,
                source: bill.args.source,
                orders_code:bill.args.orders_code,
                bill_type:bill.args.billType
            },
            call: function( o ) {
                if (o.code == 200 && o.data) {

                    //商品促销信息
                    var goods_array = o.data.goods;

                    $.each( goods_array,function(k, v) {

                        $('#goods_' + k).find('.pomotion_info').html(v.goods_promotion_info);
                        $('#goods_' + k).find(".price span").html(parseFloat(v.price).toFixed(2));
                        bill.generalGoods.general_data[k]['price'] = goods_array[k].price

                    });

                    //订单促销信息
                    if (o.data.bill_promotion) {

                        var html = '';
                        $.each(o.data.bill_promotion,function(k, v){
                            html += '<li class="list-group-item">' + v + '</li>';
                        });

                        $('#promotionBill').show().find('ul').html(html);

                    } else {

                        $('#promotionBill').hide().find('ul').empty();

                    }

                    //金额计算
                    var total = o.data.total;

                    bill.global.card_is_invoice = total.card_is_invoice;

                    //发票
                    if(total.total_receivable_money == 0 || bill.global.card_is_invoice == 0){

//                        $('#invoice-square-radio-0').iCheck('check');
                        $('input[name=invoice-radio]').iCheck('uncheck');

                        $('#invoice_list').siblings('li').find('input').attr('disabled', true);
                        $('#invoice_list').find('button').attr('disabled', true);
                        $('#invoice_list').siblings('li').find('.op a').hide();

                    }

                    if(total.total_receivable_money > 0 && bill.global.card_is_invoice == 1){

                        if(bill.args.buy_log.invoiceID > 0)
                            $('#invoice-square-radio-' + bill.args.buy_log.invoiceID).iCheck('check');

                        $('#invoice_list').siblings('li').find('input').attr('disabled', false);
                        $('#invoice_list').find('button').attr('disabled', false);
                    }

                    if(bill.global.card_is_invoice == 0 && total.total_receivable_money > 0){
                        $('#card_is_invoice_sign').html('(使用了特殊卡支付，不能开具发票)');
                    }else{
                        $('#card_is_invoice_sign').html('');
                    }

                    var t = $('#billType').val();
                    //订单应收为0
                    if(t==2 || t==7 || t==3 || t==5){

                        total.total_points = 0;
                        total.total_subtract_money = 0;
                        total.total_receivable_money = 0;

                    }

                    $(".freight_noAuth").text(parseFloat(total.deliver_feePaid).toFixed(2)); //运费
                    $("#alterFreight").val(parseFloat(total.deliver_feePaid).toFixed(2)); //运费
                    $('#deliver_feePaid').text(parseFloat(total.deliver_feePaid).toFixed(2));    //实际运费
                    $('#bill_totalPaid').text(total.bill_totalPaid.toFixed(2));                 //商品总金额
                    $('#bill_money').text(total.bill_money.toFixed(2));                 //订单金额
                    $('#total_receivable_money').text(total.total_receivable_money.toFixed(2));//应收金额
                    $('#total_subtract_money').text(total.total_subtract_money.toFixed(2));
                    $('#total_amount').text(total.total_amount);
                    $('#total_points').text(total.total_points);

                    bill.args.total = total;

                }
            }
        });
    }

};


bill.deliver = {

    d_data: { },
    

    createAddressList: function(o) 
    {
        if (this.d_data[o.deliverID]) {

            var address_list = o.custName + '，' ;
            if (o.mobile) {
                address_list += o.provinceName + o.cityName + o.countyName + ' ' + o.address + '，' + o.mobile;
                if(o.type == 2){
                    address_list += '<span style="color: red;">&nbsp;&nbsp;自提站点</span>';
                }
            } else {
                address_list += o.provinceName + o.cityName + o.countyName + ' ' + o.address + '，' + o.phone;
                if(o.type == 2){
                    address_list += '<span style="color: red;">&nbsp;&nbsp;自提站点</span>';
                }
            }

            $('label[for="deliver-square-radio-' + o.deliverID + '"]').html(address_list);

        } else {

            //add by 20141111 sunqiang FUN-BK-0021 订单为已下车状态可修改订单 start
//            var address_list = '<li class="list-group-item">';
//            if (o.deliverID == bill.args.buy_log.deliverID) {
//                address_list += '<input type="radio" id="deliver-square-radio-' + o.deliverID + '" name="deliver-square-radio" checked>';
//
//
//                address_list += '<label for="deliver-square-radio-' + o.deliverID + '">';
//                address_list += o.custName + '，' ;
//
//                if (o.mobile) {
//                    address_list += o.provinceName + o.cityName + o.countyName + ' ' + o.address + '，' + o.mobile;
//                } else {
//                    address_list += o.provinceName + o.cityName + o.countyName + ' ' + o.address + '，' + o.phone;
//                }
//
//                if(o.type == 2){
//                    address_list += '<span style="color: red;">&nbsp;&nbsp;自提站点</span>';
//                }
//
//                address_list += '</label>';
//                address_list += '<span class="op">';
//                address_list += '<button type="button" class="btn btn-success btn-xs" onclick="bill.map.open(' + o.deliverID + ')">查看地图</button>&nbsp;&nbsp;';
//
//                //自提
//                if(o.type == 2) {
//                    address_list += '<a href="javascript: void(0);" onclick="bill.take.open(' + o.deliverID + ');">[修改]</a>&nbsp;&nbsp;';
//                }
//            } else {
//                if(bill.args.bill_status != 5 && bill.args.bill_status != 6)
//                {
//                    address_list += '<input type="radio" id="deliver-square-radio-' + o.deliverID + '" name="deliver-square-radio">';
//                }
//            }






            if(bill.args.bill_status != 5 && bill.args.bill_status != 6)
            {
                var address_list = '<li class="list-group-item">';
                if (o.deliverID == bill.args.buy_log.deliverID) {
                    address_list += '<input type="radio" id="deliver-square-radio-' + o.deliverID + '" name="deliver-square-radio" checked>';
                } else {
                    address_list += '<input type="radio" id="deliver-square-radio-' + o.deliverID + '" name="deliver-square-radio">';
                }

                address_list += '<label for="deliver-square-radio-' + o.deliverID + '">';
                address_list += o.custName + '，' ;

                if (o.mobile) {
                    address_list += o.provinceName + o.cityName + o.countyName + ' ' + o.address + '，' + o.mobile;
                } else {
                    address_list += o.provinceName + o.cityName + o.countyName + ' ' + o.address + '，' + o.phone;
                }

                if(o.type == 2){
                    address_list += '<span style="color: red;">&nbsp;&nbsp;自提站点</span>';
                }

                address_list += '</label>';
                address_list += '<span class="op">';
                address_list += '<button type="button" class="btn btn-success btn-xs" onclick="bill.map.open(' + o.deliverID + ')">查看地图</button>&nbsp;&nbsp;';
                //自提
                if(o.type == 2) {
                    address_list += '<a href="javascript: void(0);" onclick="bill.take.open(' + o.deliverID + ');">[修改]</a>&nbsp;&nbsp;';
                }
                if(o.type == 1) {
                    address_list += '<a href="javascript: void(0);" onclick="bill.deliver.alter.open(' + o.deliverID + ');">[修改]</a>&nbsp;&nbsp;';
                }
                address_list += '<a href="javascript: void(0);" onclick="bill.deliver.del.open(' + o.deliverID + ');" >[删除]</a>';
                address_list += '</span>';
                address_list += '</li>';
            }
            else
            {
                if (o.deliverID == bill.args.buy_log.deliverID) {
                    var address_list = '<li class="list-group-item">';
                    address_list += '<input type="radio" id="deliver-square-radio-' + o.deliverID + '" name="deliver-square-radio" checked>';
                    address_list += '<label for="deliver-square-radio-' + o.deliverID + '">';
                    address_list += o.custName + '，' ;
                    if (o.mobile) {
                        address_list += o.provinceName + o.cityName + o.countyName + ' ' + o.address + '，' + o.mobile;
                    } else {
                        address_list += o.provinceName + o.cityName + o.countyName + ' ' + o.address + '，' + o.phone;
                    }
                    if(o.type == 2){
                        address_list += '<span style="color: red;">&nbsp;&nbsp;自提站点</span>';
                    }
                    address_list += '</label>';
                    address_list += '<span class="op">';
                    address_list += '<button type="button" class="btn btn-success btn-xs" onclick="bill.map.open(' + o.deliverID + ')">查看地图</button>&nbsp;&nbsp;';
                    address_list += '</span>';
                    address_list += '</li>';
                }

            }








            //add by 20141111 sunqiang FUN-BK-0021 订单为已下车状态可修改订单 end

//del by 20141111 sunqiang FUN-BK-0021 订单为已下车状态可修改订单 start
//            var address_list = '<li class="list-group-item">';
//            if (o.deliverID == bill.args.buy_log.deliverID) {
//                address_list += '<input type="radio" id="deliver-square-radio-' + o.deliverID + '" name="deliver-square-radio" checked>';
//            } else {
//                address_list += '<input type="radio" id="deliver-square-radio-' + o.deliverID + '" name="deliver-square-radio">';
//            }
//
//            address_list += '<label for="deliver-square-radio-' + o.deliverID + '">';
//            address_list += o.custName + '，' ;
//
//            if (o.mobile) {
//                address_list += o.provinceName + o.cityName + o.countyName + ' ' + o.address + '，' + o.mobile;
//            } else {
//                address_list += o.provinceName + o.cityName + o.countyName + ' ' + o.address + '，' + o.phone;
//            }
//
//            if(o.type == 2){
//                address_list += '<span style="color: red;">&nbsp;&nbsp;自提站点</span>';
//            }
//
//            address_list += '</label>';
//            address_list += '<span class="op">';
//            address_list += '<button type="button" class="btn btn-success btn-xs" onclick="bill.map.open(' + o.deliverID + ')">查看地图</button>&nbsp;&nbsp;';
//
//            //自提
//            if(o.type == 2) {
//                address_list += '<a href="javascript: void(0);" onclick="bill.take.open(' + o.deliverID + ');">[修改]</a>&nbsp;&nbsp;';
//            }
//
//
//
//            //地址
//            if(o.type == 1) {
//                address_list += '<a href="javascript: void(0);" onclick="bill.deliver.alter.open(' + o.deliverID + ');">[修改]</a>&nbsp;&nbsp;';
//            }
//            address_list += '<a href="javascript: void(0);" onclick="bill.deliver.del.open(' + o.deliverID + ');" >[删除]</a>';
//
//
//            address_list += '</span>';
//            address_list += '</li>';
//del by 20141111 sunqiang FUN-BK-0021 订单为已下车状态可修改订单 end




            $('#address_list').before(address_list);
            $('#deliver-square-radio-' + o.deliverID).iCheck({
                checkboxClass: 'icheckbox_square-blue',
                radioClass: 'iradio_square-blue',
                increaseArea: '20%' // optional
            });

            $('#deliver-square-radio-' + o.deliverID).on('ifClicked', function() {
                bill.deliver.choose.start(o.deliverID);
            });

        }

        this.d_data[o.deliverID] = o;

    },

    choose: {

        start: function( id ) {

            if (bill.args.buy_log.deliverID == id)
                return false;

            E.loadding.open('正在查询收货地址，请稍候...');

            E.ajax_post({
                url: '/invokingAjax-comm/bill/checkout.ajax?operFlg=2',
                data: {
                    buy_log: bill.args.buy_log,
                    deliverID: id,
                    source: bill.args.source,
                    orders_code:bill.args.orders_code
                },
                call: 'bill.deliver.choose.result'
            });

        },

        result: function( o ) {

            E.loadding.close();

            if (o.code == 200) {

                var log = o.data.log;
                var d = bill.define;

                $('#deliver-square-radio-' + log.deliverID).iCheck('check');
                $('#send_list').html('');
                $('#pay_list').html('');

                //收货地址ID
                bill.args.buy_log.deliverID = log.deliverID;

                if (!o.data.send) { //没有配送方式

                    bill.send.create.error(d.n_send);
                    bill.pay.create.error(d.s_pay);

                } else {

                    //配送区域ID
                    bill.args.buy_log.send_region_id = log.send_region_id;

                    if (o.data.distribution) {
                        $('#distribution').html(o.data.distribution.distribution_name);
                        //add yim.hu 20141126 FUN-BK-0036  新增订单爆单提示 --start
                        //给一个配送站ID方便查询数据
                        $('#distribution').attr('key',o.data.distribution.distribution_id);
                        //add yim.hu 20141126 FUN-BK-0036 新增订单爆单提示 --end
                    } else {
                        $('#distribution').html('未匹配到配送站');
                    }

                    //显示配送方式
                    bill.send.create.list( o.data.send );

                    if (!o.data.pay || o.data.pay.length == 0) { //没有支付方式

                        bill.pay.create.error(d.n_pay);

                    } else {

                        //支付方式ID和支付类型
                        bill.args.buy_log.payTypeID = log.payTypeID;
                        bill.args.buy_log.pay_type = log.pay_type;

                        //显示支付方式
                        bill.pay.create.list( o.data.pay );

                        if(o.data.payment){

                            bill.args.buy_log.payment_method_id = log.payment_method_id;

                            //显示付款方式
                            bill.payment.create.list( o.data.payment );
                        }
                    }
                }

                if (o.data.freight) {
                    bill.args.freight = parseFloat(o.data.freight);
                }
                //add yim.hu 20141126 FUN-BK-0036  新增订单爆单提示--start
                
                E.loadding.open('正在努力加载中...');
                //开始判断爆单的时间
    			$.ajax({
    	            url: "/invokingAjax-shop/default/checkout.ajax?operFlg=24",
    	            data: {
    	            	distribution_id : o.data.distribution.distribution_id,
    	            	send_date	:  $('#send_date').val()

    	            },
    	            type: "POST",
    	            success: function(data){
    	            	$('#tishi_baodan').hide();
    	            	E.loadding.close();
    	            	var data = eval('(' + data + ')');

                        var time_str = $('#start_time').val().split(',')[0];

                        //先清空开始时间
	            		$('#start_time').html('');
	            		
	            		$('#start_time').append("<option value=''>请选择开始时间</option>")
	            		$.each(data,function(i,key){

                            var isselected = "";
                            if(key.itemName ==time_str)
                            {
                                isselected = "selected";
                            }
                            if(key.h==1){
	            				if($('#send_time_text').is(":hidden")==false){
	            					$('#tishi_baodan').show();
	            				}	            				
	            				$('#start_time').append("<option value='"+key.itemName+",1' " +isselected + " >"+key.itemName+" (爆单)</option>")
	            			}else{
	            				$('#start_time').append("<option value='"+key.itemName+"' " +isselected + " >"+key.itemName+"</option>")

	            			}
	            			
	            		}); 	
    	            }            
    	        });   
                
                //add yim.hu 20141126 FUN-BK-0036 新增订单爆单提示 --end
                //检查商品促销活动、订单促销、计算金额
                bill.global.total();

            } 
        }

    },

    alter: {

        open: function( id ) {

            var html = '<form class="form-horizontal" role="form" id="address_form">';

            html += '<div class="form-group">';
            html += '<label for="custName" class="col-sm-2 control-label">收货人</label>';
            html += '<div class="col-sm-10">';
            html += '<input type="text" class="form-control" id="custName" name="custName" placeholder="收货人" style="width: 150px;">';
            html += '</div>';
            html += '</div>';

            html += '<div class="form-group">';
            html += '<label for="province_list" class="col-sm-2 control-label">所在地区</label>';
            html += '<div class="col-sm-10">';
            html += '<select class="form-control col-sm-2" id="province_list" name="provinceid" style="width: 150px;margin-right: 10px;"><option value="0">请选择...</option></select>';
            html += '<select class="form-control col-sm-2" id="city_list" name="cityid" style="width: 150px;margin-right: 10px;"><option value="0">请选择...</option></select>';
            html += '<select class="form-control col-sm-2" id="county_list" name="countyid" style="width: 150px;"><option value="0">请选择...</option></select>';
            html += '</div>';
            html += '</div>';

            html += '<div class="form-group">';
            html += '<label for="address" class="col-sm-2 control-label">收货地址</label>';
            html += '<div class="col-sm-10">';
            html += '<input type="text" class="form-control" id="address" name="address" placeholder="收货地址">';
            html += '</div>';
            html += '</div>';

            html += '<div class="form-group">';
            html += '<label for="mobile" class="col-sm-2 control-label">手机号码</label>';
            html += '<div class="col-sm-10">';
            html += '<input type="text" class="form-control" id="mobile" name="mobile" placeholder="手机号码" style="width: 150px;">';
            html += '</div>';
            html += '</div>';

            html += '<div class="form-group">';
            html += '<label for="phone" class="col-sm-2 control-label">固定电话</label>';
            html += '<div class="col-sm-10">';
            html += '<input type="text" class="form-control" id="phone" name="phone" placeholder="固定电话" style="width: 150px;">';
            html += '<span class="help-block red">“手机号码”和“固定电话”至少填写一项</span>';
            html += '<input type="hidden" name="pcustID" value="' + bill.args.pcustID + '">';
            html += '<input type="hidden" name="deliverID" id="deliverID" value="0">';
            html += '</div>';
            html += '</div>';

            html += '</form>';
            
            E.popup.open({
                title: id == 0 ? '新增收货地址' : '修改收货地址',
                content: html,
                btnName: id == 0 ? '添加' : '修改',
                css: 'width: 624px;',
                btnCall: "E.region.backAdd('address_form', 'bill.deliver.alter.result');"
            });
           
            	
            var cityid = $("#billCity").val();
            var provinceid = $("#billCity").find("option[value='"+ cityid +"']").attr('pro');
            if (id == 0) {
                E.region.init({
                    pid: provinceid,
                    cid: cityid,
                    pShow: 'n',
                    cShow: 'n'
                });
                $('#custName').val(bill.args.custname);
                $('#mobile').val(bill.args.mobile);
            } else {
                var deliver_array = bill.deliver.d_data[id];
                $('#custName').val(deliver_array.custName);
                E.region.init({
                    pid: deliver_array.provinceid,
                    cid: deliver_array.cityid,
                    ccid: deliver_array.countyid,
                    pShow: 'n',
                    cShow: 'n'
                });
                $('#address').val(deliver_array.address);
                $('#mobile').val(deliver_array.mobile);
                $('#phone').val(deliver_array.phone);
                $('#deliverID').val(deliver_array.deliverID);
            }

        },

        result: function( o ) {

            E.loadding.close();
            if (o.code == 200) {

                E.popup.close();

                var is_ajax_load = false;
                if (o.data.deliverID || o.data.deliverID == bill.args.buy_log.deliverID) {
                    is_ajax_load = true;
                    bill.args.buy_log.deliverID = "";
                } else if (Object.keys(bill.deliver.d_data).length == 0)
                    is_ajax_load = true;

                bill.deliver.createAddressList( o.data );

                if (is_ajax_load)
                    bill.deliver.choose.start(o.data.deliverID);

            } else {

                E.alert(o.message);
            }
        }

    },


    del: {

        open: function( id ) {
            this.tempID = id;
            E.confirm("您确定要删除该收货地址吗？", "bill.deliver.del.confirm");
        },

        confirm: function() {
            E.loadding.open("正在删除收货地址，请稍候...");
            E.ajax_get({
                url: "/invokingAjax-backend/customer/deliver.ajax?operFlg=2",
                data: {
                    id: this.tempID,
                    pcustID: bill.args.pcustID,
                    orders_code:bill.args.orders_code
                },
                call: "bill.deliver.del.result"
            });

        },

        result: function( o ) {

            E.loadding.close();

            if (o.code == 200) {

                delete bill.deliver.d_data[this.tempID];
                $('#deliver-square-radio-' + this.tempID).parent().parent().remove();

                if (this.tempID == bill.args.buy_log.deliverID) {

                    var deliverID = '';
                    $.each(bill.deliver.d_data, function(k, v) {
                        deliverID = k;
                        return false;
                    });

                    if (deliverID) {

                        bill.deliver.choose.start(deliverID);

                    } else {

                        bill.deliver.alter.open(0);
                        $("#send_list").html("");
                        $("#pay_list").html("");
                        bill.send.create.error(bill.define.d_send);
                        bill.pay.create.error(bill.define.s_pay);

                    }
                }
            } else {
                E.alert(o.message);
            }

        }

    }

};

//自提站点类
bill.take = {

    temp_id:0,

    open:function(id){

        bill.take.temp_id = id;

        var cityid = $("#billCity").val();
        E.loadding.open('正在努力为您加载中...');
        E.ajax_post({
            action:'checkout',
            operFlg:3,
            data: {
                pcustID: bill.args.pcustID,
                buy_log: bill.args.buy_log,
                cityid: cityid,
                orders_code:bill.args.orders_code
            },
            call: 'bill.take.openResult'
        });

    },

    openResult:function(o){

        var deliverID = bill.take.temp_id;
        E.loadding.close();

        if(o.code == 200){

            var html = '<div style="width: 778px;height:390px;overflow:hidden;">';
            html += '<div style="width: 326px;height:350px;float:left">';
            html += '<form class="form-horizontal" role="form" id="distributionForm">';
            html += '<table width="100%" class="table table-condensed">';
            $.each(o.data, function(k, v){

                html += '<tr class="active" width="20%">';
                html += '<td width="30%" colspan="2"><input type="radio" cityName="'+ v.cityName +'" address="'+ v.address +'" id="take-square-radio-'+ v.distribution_id +'" name="distribution_id" value="'+ v.distribution_id +'">&nbsp;'+ v.distribution_name +':</td>';
                html += '<td>'+ v.address;
                html += '<input type="hidden" name="provinceid" value="'+ v.provinceid +'">';
                html += '<input type="hidden" name="cityid" value="'+ v.cityid +'">';
                html += '<input type="hidden" name="countyid" value="'+ v.countyid +'">';
                html += '<input type="hidden" name="address" value="'+ v.address +'">';
                html += '<input type="hidden" name="type" value="2">';
                html += '<input type="hidden" name="pcustID" value="' + bill.args.pcustID + '">';
                html += '<input type="hidden" name="deliverID" value="' + deliverID+ '">';
                html += '</td>';
                html += '</tr>';

            });
            html += '</table>';
            html += '<div style="width:100%;height:70px;">';

            html += '<div class="form-group">';
            html += '<label for="custName" class="col-sm-3 control-label">收货人</label>';
            html += '<div class="col-sm-8">';
            html += '<input type="email" class="form-control" name="custName" id="custName" value="' + bill.args.custname + '" placeholder="请输入收货人姓名">';
            html += '</div>';
            html += '</div>';

            html += '<div class="form-group">';
            html += '<label for="mobile" class="col-sm-3 control-label">手机号</label>';
            html += '<div class="col-sm-8">';
            html += '<input type="email" class="form-control" name="mobile" id="mobile" value="' + bill.args.mobile + '" placeholder="请输入手机号码">';
            html += '</div>';
            html += '</div>';

            html += '</form>';

            html += '</div>';
            html += '</div>';

            html += '<div style="width: 450px;height:350px;float:right;" id="take_map"></div>';
            html += '</div>';

            E.popup.open({
                title: '选择自提点',
                content:html,
                css: 'width:800px',
                btnName: deliverID ? '修改自提点' : '新增自提点',
                btnCall: "bill.take.add();"
            });

            $("input[name='distribution_id']").iCheck({
                checkboxClass: 'icheckbox_square-blue',
                radioClass: 'iradio_square-blue',
                increaseArea: '20%' // optional
            });


            mapMarker.M_type = 2;

            $("input[name='distribution_id']").on('ifChecked', function(event){

                var cityName = $(this).attr('cityName');
                var address = $(this).attr('address');

                mapMarker.M_city = cityName;
                mapMarker.M_address = address;
                mapMarker.M_type = 1;

                map.city_name = cityName;
                map.G_id = 'take_map';
                map.G_zoom = 10;
                //del 20141124 sunqiang  FUN-BK-0034 运费规则调整 start
                //map.G_type = 1;
                //del 20141124 sunqiang  FUN-BK-0034 运费规则调整 end
                map.setMap();
                mapArea.search();
            });

            if(deliverID> 0){

                var deliver_array = bill.deliver.d_data[deliverID];

                mapMarker.M_address = deliver_array.address;
                mapMarker.M_city = deliver_array.cityName;
                mapMarker.M_type = 1;

                $("#custName").val(deliver_array.custName);
                $("#mobile").val(deliver_array.mobile);
                $('#take-square-radio-' + deliver_array.distribution_id).iCheck('check');

                cityName = deliver_array.cityName;
                cityid = deliver_array.cityid;

            }else{
                var cityid = $("#billCity").val();

                if(bill.args.deliver_city){
                    var cityName = bill.args.deliver_city;
                }else{
                    var cityName = $("#billCity option:selected").text();
                }
            }
            map.city_name = cityName;
            map.G_id = 'take_map';
            map.G_cityid = cityid;
            map.G_zoom = 10;
            //del 20141124 sunqiang  FUN-BK-0034 运费规则调整 start
            //map.G_type = 1;
            //del 20141124 sunqiang  FUN-BK-0034 运费规则调整 end
            map.setMap();
            mapArea.search();

        }else{
            E.alert(o.message);
        }

    },

    add:function(){

        var id = 'distributionForm';
        var dt = E.getFormValues(id);

        if(E.isEmpty(dt.distribution_id)){
            E.alert('配送站必须选择');
            return false;
        }

        E.region.backAdd(id, 'bill.deliver.alter.result');

    }



}


bill.send = {

    create: {

        list: function( send_obj ) {

            $.each(send_obj, function(k, v) {

                var send_list = '<li class="list-group-item">';
                if (v.send_region_id == bill.args.buy_log.send_region_id) {
                    send_list += '<input type="radio" id="send-square-radio-' + v.send_region_id + '" name="send-square-radio" checked>';
                } else {
                    send_list += '<input type="radio" id="send-square-radio-' + v.send_region_id + '" name="send-square-radio">';
                }
                if (v.description) {
                    send_list += '<label for="send-square-radio-' + v.send_region_id + '">' + v.sendTypeName + '，' + v.description + '</label>';
                } else {
                    send_list += '<label for="send-square-radio-' + v.send_region_id + '">' + v.sendTypeName + '</label>';
                }

                send_list += '</li>';
                $('#send_list').append(send_list);
                $('#send-square-radio-' + v.send_region_id).iCheck({
                    checkboxClass: 'icheckbox_square-blue',
                    radioClass: 'iradio_square-blue',
                    increaseArea: '20%' // optional
                });

                $('#send-square-radio-' + v.send_region_id).on('ifClicked', function() {
                    bill.send.choose.start(v.send_region_id);
                });

                if (v.is_match == 0) {
                    $('#no_match').text('超出配送范围及运费范围');
                } else {
                    $('#no_match').text('');
                }

            });

        },

        error: function( msg ) {
            var html = '<li class="list-group-item red">' + msg + '</li>';
            $("#send_list").append(html);
        }

    },

    choose: {

        start: function( id ) {

            if (bill.args.buy_log.send_region_id == id)
                return false;

            E.loadding.open("正在查询配送方式，请稍候...");

            E.ajax_post({
                url: "/invokingAjax-comm/bill/checkout.ajax?operFlg=3",
                data: {
                    buy_log: bill.args.buy_log,
                    send_region_id: id,
                    source: bill.args.source,
                    orders_code:bill.args.orders_code
                },
                call: "bill.send.choose.result"
            });

        },

        result: function( o ) {

            E.loadding.close();
            if (o.code == 200) {

                var log = o.data.log;
                var d = bill.define;

                $('#pay_list').html('');

                //配送区域ID
                bill.args.buy_log.send_region_id = log.send_region_id;

                if (o.data.pay) {

                    //支付方式ID和支付类型
                    bill.args.buy_log.payTypeID = log.payTypeID;
                    bill.args.buy_log.pay_type = log.pay_type;

                    //显示支付方式
                    bill.pay.create.list( o.data.pay );

                } else {

                    bill.pay.create.error(d.n_pay);

                }

                bill.global.total();

                //运费
                if (o.data.freight) {
                    bill.args.freight = parseFloat(o.data.freight);
                    bill.global.compute();
                }

            } else {

                E.alert(o.message);

            }
        }

    }

};


bill.pay = {

    create: {

        list: function( pay_obj ) {

            $.each(pay_obj, function(k, v) {

                $.each(v.list, function(i, j) {

                    var pay_list = '<li class="list-group-item">';
                    if (j.payTypeID == bill.args.buy_log.payTypeID) {
                        pay_list += '<input type="radio" id="pay-square-radio-' + j.payTypeID + '" name="pay-square-radio" checked>';
                    } else {
                        pay_list += '<input type="radio" id="pay-square-radio-' + j.payTypeID + '" name="pay-square-radio">';
                    }

                    pay_list += '<label for="pay-square-radio-' + j.payTypeID + '">' + j.payTypeName + '</label>';
                    pay_list += '</li>';
                    $('#pay_list').append(pay_list);

                    $('#pay-square-radio-' + j.payTypeID).iCheck({
                        checkboxClass: 'icheckbox_square-blue',
                        radioClass: 'iradio_square-blue',
                        increaseArea: '20%' // optional
                    });

                    $('#pay-square-radio-' + j.payTypeID).on('ifClicked', function() {
                        bill.pay.choose( j.payTypeID );
                    });

                    if (j.type == 1 && j.list) {

                        if (j.payTypeID == bill.args.buy_log.payTypeID) {
                            var pay_list = '<li style="margin-left: 30px; padding:10px;" id="m_pay_'+ j.payTypeID +'" class="m_pay"></li>';
                        } else {
                            var pay_list = '<li style="margin-left: 30px; padding:10px; display: none;" id="m_pay_'+ j.payTypeID +'" class="m_pay"></li>';
                        }

                        $('#pay_list').append(pay_list);

                        $.each(j.list, function(m, n) {

                            var m_pay_list = '<span class="bill-pay-ment-list">';
                            if (n.id == bill.args.buy_log.payment_method_id) {
                                m_pay_list += '<input type="radio" id="m_pay-square-radio-' + n.id + '" name="m_pay-square-radio" checked>';
                            } else {
                                m_pay_list += '<input type="radio" id="m_pay-square-radio-' + n.id + '" name="m_pay-square-radio">';
                            }
                            m_pay_list += '<label for="m_pay-square-radio-' + n.id + '">' + n.name + '</label>';
                            m_pay_list += '</span>&nbsp;&nbsp;&nbsp;&nbsp;';
                            $("#m_pay_" + j.payTypeID).append(m_pay_list);

                            $('#m_pay-square-radio-' + n.id).iCheck({
                                checkboxClass: 'icheckbox_square-blue',
                                radioClass: 'iradio_square-blue',
                                increaseArea: '20%' // optional
                            });

                            $('#m_pay-square-radio-' + n.id).on('ifChecked', function() {
                                bill.pay.choosePayment( n.id );
                            });

                        });

                    }

                });

            });

        },

        error: function( msg ) {
            var html = '<li class="list-group-item red">' + msg + '</li>';
            $('#pay_list').append(html);
        }

    },

    choose: function( id ) {

        if (bill.args.buy_log.payTypeID == id)
            return false;

        E.loadding.open('正在查询支付方式，请稍候...');
        E.ajax_post({
            url: '/invokingAjax-comm/bill/checkout.ajax?operFlg=4',
            data: {
                payTypeID: id,
                buy_log: bill.args.buy_log,
                source: bill.args.source,
                orders_code:bill.args.orders_code
            },
            call: function( o ) {

                E.loadding.close();

                if (o.code == 200) {

                    var log = o.data.log;

                    //支付方式ID和支付类型
                    bill.args.buy_log.payTypeID = log.payTypeID;
                    bill.args.buy_log.pay_type = log.pay_type;
                    bill.args.buy_log.payment_method_id = log.payment_method_id;

                    $('.m_pay').hide();
                    $('input[name=m_pay-square-radio]').iCheck('uncheck');
                    bill.args.buy_log.payment_method_id = '';
                    if (log.pay_type == 1) {
                        $('#m_pay_' + bill.args.buy_log.payTypeID).show();
                    } else {

                        //检查商品促销活动、订单促销、计算金额
                        bill.global.total();
                    }

                } else {
                    E.alert(o.message);
                }

            }
        });

    },

    //选择付款方式
    choosePayment: function(id) {

        if (bill.args.buy_log.payment_method_id == id)
            return false;

        E.loadding.open('正在查询付现方式，请稍候...');
        E.ajax_post({
            url: '/invokingAjax-comm/bill/checkout.ajax?operFlg=5',
            data: {
                payment_method_id: id,
                buy_log: bill.args.buy_log,
                source: bill.args.source,
                orders_code:bill.args.orders_code
            },
            call: function( o ) {

                E.loadding.close();

                if (o.code == 200) {

                    //支付方式ID和支付类型
                    bill.args.buy_log.payment_method_id = o.data.log.payment_method_id;

                    //检查商品促销活动、订单促销、计算金额
                    bill.global.total();

                } else {
                    E.alert(o.message);
                }

            }
        });

    }

};

bill.invoice = {

    i_data: { },

    createInvoiceList: function( o ) {

        if (this.i_data[o.invoiceID]) {

            var invoice_list = '';
            if (o.invoice_title_type == 1){
                invoice_list += '商业零售发票(个人)';
            } else {
                invoice_list += '商业零售发票(单位)';
            }
            invoice_list += '(发票抬头：' + o.invoice_title + ')';
            $('label[for="invoice-square-radio-' + o.invoiceID + '"]').text(invoice_list);

        } else {

            var invoice_list = '<li class="list-group-item">';
            if (o.invoiceID == bill.args.buy_log.invoiceID) {

                invoice_list += '<input type="radio" id="invoice-square-radio-' + o.invoiceID + '" name="invoice-radio" checked>';
            } else {
                invoice_list += '<input type="radio" id="invoice-square-radio-' + o.invoiceID + '" name="invoice-radio">';
            }

            invoice_list += '<label for="invoice-square-radio-' + o.invoiceID + '">';
            if (o.invoice_title_type == 1){
                invoice_list += '商业零售发票(个人)';
            } else {
                invoice_list += '商业零售发票(单位)';
            }
            invoice_list += '(发票抬头：' + o.invoice_title + ')';
            invoice_list += '</label>';
            invoice_list += '<span class="op">';
            invoice_list += '<a href="javascript: void(0);" onclick="bill.invoice.edit.open(' + o.invoiceID + ');">[修改]</a>&nbsp;&nbsp;';
            invoice_list += '<a href="javascript: void(0);" onclick="bill.invoice.del.open(' + o.invoiceID + ');" >[删除]</a>';
            invoice_list += '</span>';
            invoice_list += '</li>';

            $("#invoice_list").before(invoice_list);

            $('#invoice-square-radio-' + o.invoiceID).iCheck({
                checkboxClass: 'icheckbox_square-blue',
                radioClass: 'iradio_square-blue',
                increaseArea: '20%' // optional
            });

            $('#invoice-square-radio-' + o.invoiceID).on('ifClicked', function() {
                bill.invoice.choose.start(o.invoiceID);
            });

        }

        this.i_data[o.invoiceID] = o;

    },

    choose: {

        start: function( id ) {

            if (bill.args.buy_log.invoiceID == id)
                return false;

            E.loadding.open("正在查询发票，请稍候...");
            E.ajax_post({
                url: "/invokingAjax-comm/bill/checkout.ajax?operFlg=6",
                data: {
                    invoiceID: id,
                    buy_log: bill.args.buy_log,
                    source: bill.args.source,
                    orders_code:bill.args.orders_code
                },
                call: "bill.invoice.choose.result"
            });

        },

        result: function( o ) {

            E.loadding.close();
            if (o.code == 200) {
                $('#invoice-square-radio-' + o.data.log.invoiceID).iCheck('check');
                bill.args.buy_log.invoiceID = o.data.log.invoiceID;

            } else {
                E.alert(o.message);
            }

        }

    },

    edit: {

        open: function(id) {

            var html = '<div class="form-horizontal" id="address_form">';

            html += '<div class="form-group">';
            html += '<label for="invoice_type" class="col-sm-2 control-label">发票类型</label>';
            html += '<div class="col-sm-10">';
            html += '<select class="form-control" id="invoice_type" name="invoice_type" style="width: 150px;margin-right: 10px;">';
            html += '<option value="1">商业零售发票</option>';
            html += '</select>';
            html += '</div>';
            html += '</div>';

            html += '<div class="form-group">';
            html += '<label for="invoice_title" class="col-sm-2 control-label">发票抬头</label>';
            html += '<div class="col-sm-10">';
            html += '<select class="form-control col-sm-2" id="invoice_title_type" name="invoice_title_type" style="width: 150px;margin-right: 10px;">';
            html += '<option value="1">个人</option>';
            html += '<option value="2">单位</option>';
            html += '</select>';
            html += '<input type="text" class="form-control col-sm-2" id="invoice_title" name="invoice_title" placeholder="发票抬头" style="width: 280px;">';
            html += '<input type="hidden" value="0" id="invoiceID">';
            html += '</div>';
            html += '</div>';

            html += '</div>';

            E.popup.open({
                title: id == 0 ? "新增发票" : "修改发票",
                content: html,
                css: 'width: 600px;',
                btnName: '保存',
                btnCall: "bill.invoice.edit.submit();"
            });

            if (id > 0) {
                $("#invoice_title").val(bill.invoice.i_data[id]['invoice_title']);
                $("#invoice_title_type").val(bill.invoice.i_data[id]['invoice_title_type']);
                $("#invoiceID").val(bill.invoice.i_data[id]['invoiceID']);
            }

        },

        submit: function() {

            var invoice_title = E.trim($("#invoice_title").val());
            var invoice_title_type = $("#invoice_title_type").val();

            if (E.empty(invoice_title) && invoice_title_type != 1)
                E.alert("发票抬头不能为空，请填写");
            else {
                E.loadding.open("正在保存发票信息，请稍等...");
                E.ajax_post({
                    url: "/invokingAjax-backend/customer/invoice.ajax?operFlg=1",
                    data: {
                        invoice_title: invoice_title,
                        invoice_type: $("#invoice_type").val(),
                        invoice_title_type: invoice_title_type,
                        invoiceID: $("#invoiceID").val(),
                        pcustID: bill.args.pcustID
                    },
                    call: "bill.invoice.edit.result"
                });
            }

        },

        result: function( o ) {

            E.loadding.close();
            if (o.code == 200) {

                E.popup.close();

                var is_ajax_load = false;
                if (o.data.invoiceID || o.data.invoiceID == bill.args.buy_log.invoiceID) {
                    is_ajax_load = true;
                    bill.args.buy_log.invoiceID = "";
                } else if (Object.keys(bill.invoice.i_data).length == 0)
                    is_ajax_load = true;

                bill.invoice.createInvoiceList( o.data );

                if (is_ajax_load)
                    bill.invoice.choose.start( o.data.invoiceID );

            } else {
                E.alert(o.message);
            }

        }

    },


    del: {

        open: function(id) {
            this.tempID = id;
            E.confirm("您确定要删除该发票吗？", "bill.invoice.del.confirm");
        },

        confirm: function() {
            E.loadding.open("正在删除发票信息，请稍等...");
            E.ajax_get({
                url: "/invokingAjax-backend/customer/invoice.ajax?operFlg=2",
                data: {
                    id: this.tempID,
                    pcustID: bill.args.pcustID
                },
                call: "bill.invoice.del.result"
            });
        },

        result: function( o ) {

            E.loadding.close();
            if (o.code == 200) {
                delete bill.invoice.i_data[this.tempID];
                $('#invoice-square-radio-' + this.tempID).parent().parent().remove();

                if (this.tempID == bill.args.buy_log.invoiceID) {
                    bill.invoice.choose.start(0);
                }
            } else {
                E.alert(o.message);
            }
        }
    }
};


bill.generalGoods = {

    fittings_data: { },

    goods_time: { },

    general_data: { },

    detail: {

        //商品查询
        search: function( choose_data ) {
        
            E.loadding.open("正在加载商品，请稍等...");
            E.ajax_post({
                url: '/invokingAjax-comm/bill/checkoutGoods.ajax?operFlg=1',
                data: {
                    choose_data: choose_data,
                    pcustID: bill.args.pcustID,
                    cityID: $("#billCity").val(),
                    source: bill.args.source,
                    orders_code:bill.args.orders_code,
                    bill_type:bill.args.billType,
                    bill_no:bill.args.bill_no
                },
                call: "bill.generalGoods.detail.result"
            });
        },


        result: function( o ) {

            E.loadding.close();

            if (o.code == 200) {

                $('#goods_code').val('');
                $.each(o.data.goods, function(k, v) {

                    var birthcard_str = '<option value="0">请选择生日牌</option>';
                    var syncopate_str = '<option value="0">不切分</option>';

                    //生日牌
                    $.each(v.birthcard,function(ke,val){
                        birthcard_str += '<option value="'+ val +'">'+ val +'</option>';
                    });

                    //切分
                    $.each(v.syncopate,function(ke,val){
                        syncopate_str += '<option value="'+ val +'">'+ val +'</option>';
                    });

                    var goods_html = [
                        '<tr class="success" id="goods_'+ k +'">',
                        '<td>' + v.product_code + '</td>',
                        '<td>' + v.goodsName + '<div class="pomotion_info" style="color: red;font-weight: bold;"></div></td>',
                        '<td class="tac">1&nbsp</td>',
                        '<td class="tac">' + v.spec + '</td>',
                        '<td class="tac">' + parseFloat(v.salePrice).toFixed(2) + '</td>',
                        '<td class="tac price">',
                        '<span>' + parseFloat(v.price).toFixed(2) + '</span>',
                        '&nbsp;<a href="javascript:void(0);" style="display: none;" class="authPrice" onclick="bill.adjustPrice.check('+ k +');">调价</a>',
                        '</td>',
                        '<td class="tar">',
                        '<select class="form-control input-sm goods-item birthcard-select" style="width: 130px;float: left;">'+ birthcard_str +'</select>',
                        '<input type="text" name="birthcard" class="form-control input-sm birthcard" style="width:154px;" value=""></td>',
                        '<td class="tar">',
                        '<select class="form-control input-sm goods-item syncopate-select" style="width: 80px;float: left;"">'+ syncopate_str +'</select>',
                        '<input type="text" name="syncopate" class="form-control input-sm syncopate" style="width:64px;" value=""></td>',
                        '</td>',
                        '<td class="tar"><a href="javascript:void(0);" onclick="bill.generalGoods.fittings.edit('+ v.postID +','+ k +')">修改配件</a></td>',
                        '<td class="tar"><input type="text" class="form-control input-sm productRemark" style="width: 150px;" value="" name="productRemark"></td>',
                        '<td class="tac"><a class="delete_goods" href="javascript: void(0);" ebsig-data="'+ k +',general">删除</a></td>'
                    ].join('');

                    $('#general_line').append(goods_html);
                    //试吃订单无生日牌 无切分
                    if($("#billType").val()==9){
                        $(".birthcard-select").attr("disabled",true);
                        $("input[name='birthcard']").attr("disabled",true);
                        $(".syncopate-select").attr("disabled",true);
                        $("input[name='syncopate']").attr("disabled",true);

                    }

                    //页面购物车商品
                    bill.generalGoods.general_data[k] = {
                        goodsName: v.goodsName,
                        spec: v.spec,
                        price: v.price,
                        goods_amount: v.goods_amount,
                        fittings: v.fittings,            //商品配件
                        //add by 20141212 allen.qiang FUN-AC-0029-姜饼项目 start
                        product_code: v.product_code,            //商品编码
                        //add by 20141212 allen.qiang FUN-AC-0029-姜饼项目 end
                        adjustPrice: v.adjustPrice      //手动调价
                    };

                });

                //是否开启手动调价
                if(bill.args.isAuth == 1){
                    $(".authPrice").show();
                }

                //更新代金卡
                bill.card.create(o.data.card_array );

                //检查商品促销、订单促销、计算订单相关金额
                bill.global.total();

            } else {
                E.alert(o.message);
            }
        }

    },

    list: {

        choose_data: { },

        search: function( product_code, goods_name ) {

            this.product_code = product_code;
            this.goods_name = goods_name;

            E.loadding.open("正在加载商品，请稍等...");
            E.ajax_get({
                url: '/invokingAjax-comm/bill/checkoutGoods.ajax?operFlg=2',
                data: {
                    product_code: product_code,
                    goods_name: goods_name,
                    cityID:$("#billCity").val(),
                    pcustID: bill.args.pcustID,
                    source: bill.args.source,
                    orders_code:bill.args.orders_code
                },
                call: "bill.generalGoods.list.result"
            });
        },

        result: function( o ) {

            E.loadding.close();
            if (o.code == 200) {

                $('#goods_code').val('');
                $('#goods_name').val('');

                var html = '<div class="clearfix">';
                $.each(o.data, function(k, v) {
                    html += '<div class="panel panel-default" style="width: 320px;float: left;margin: 5px;">';
                    html += '<div class="panel-heading">';
                    html += '<h3 class="panel-title">' + v.goodsName + '</h3>';
                    html += '</div>';

                    html += '<ul class="list-group radio-box">';
                    $.each(v.list, function(i, j) {
                        html += '<li class="list-group-item">';
                        html += '<input type="checkbox" id="goods-square-checkbox-' + j.postID + '" name="goods-checkbox">';
                        html += '<label for="goods-square-checkbox-' + j.postID + '">' + j.spec + '</label>';
                        html += '<input type="text" class="form-control input-sm" id="goods-amount-input-'+ j.postID +'" value="1" style="width: 50px;float: right;">';
                        html += '</li>';
                    });
                    html += '</ul>';

                    html += '</div>';
                });
                html += '</div>';

                E.popup.open({
                    title: '选择商品',
                    content: html,
                    css: 'width: 700px;',
                    btnName: '选择',
                    btnCall: "bill.generalGoods.list.choose();"
                });

                var html = '<div class="clearfix">';
                $.each(o.data, function(k, v) {

                    $.each(v.list, function(i, j) {
                        $('#goods-square-checkbox-' + j.postID).iCheck({
                            checkboxClass: 'icheckbox_square-blue',
                            radioClass: 'iradio_square-blue',
                            increaseArea: '20%' // optional
                        });

                        $('#goods-square-checkbox-' + j.postID).on('ifChecked', function() {
                            bill.generalGoods.list.choose_data[j.postID] = { };
                            bill.generalGoods.list.choose_data[j.postID].product_code = j.product_code;
                        });

                        $('#goods-square-checkbox-' + j.postID).on('ifUnchecked', function() {
                            delete bill.generalGoods.list.choose_data[j.postID];
                        });
                    });
                });

            } else {
                E.alert(o.message);
            }
        },

        choose: function() {

            var product_code = '';
            $.each(bill.generalGoods.list.choose_data, function(k, v) {

                var amount = $("#goods-amount-input-"+k).val();
                if(!E.isInt(amount)){
                    E.alert('商品数量必须是非负整数');
                }

                bill.generalGoods.list.choose_data[k].amount = amount;

            });
            bill.generalGoods.detail.search(bill.generalGoods.list.choose_data);
            bill.generalGoods.list.choose_data = {};
            E.popup.close();
        }

    },

    del: {

        open: function( indexKey ) {
            this.indexKey = indexKey;
            E.confirm('您确认要删除该商品吗？', 'bill.generalGoods.del.execute');
        },

        execute: function() {

            E.loadding.open('正在删除商品，请稍候...');
            E.ajax_get({
                url: '/invokingAjax-comm/bill/checkoutGoods.ajax?operFlg=4',
                data: {
                    indexKey: this.indexKey,
                    pcustID: bill.args.pcustID,
                    source: bill.args.source,
                    orders_code:bill.args.orders_code
                },
                call: 'bill.generalGoods.del.result'
            });
        },

        result: function( o ) {

            E.loadding.close();
            if (o.code == 200) {

                $("#goods_"+this.indexKey).remove();
                delete bill.generalGoods.general_data[this.indexKey];

                //更新现金卡
                bill.card.create(o.data.card_array);

                //检查商品促销活动、订单促销、计算金额
                bill.global.total();

            } else {

                E.alert(o.message);

            }

        }

    },

    update: {

        execute: function( postID, update_amount ) {

            E.loadding.open('正在更新商品，请稍候...');
            E.ajax_get({
                url: '/invokingAjax-comm/bill/checkoutGoods.ajax?operFlg=3',
                data: {
                    postID: postID,
                    update_amount: update_amount,
                    pcustID: bill.args.pcustID,
                    source: bill.args.source,
                    orders_code:bill.args.orders_code
                },
                call: 'bill.generalGoods.update.result'
            });

        },

        result: function( o ) {

            E.loadding.close();
            if (o.code == 200) {

                if (o.data.goods_amount > 0) {
                    bill.generalGoods.general_data[o.data.postID].goods_amount = o.data.goods_amount;
                    $('#goods_amount_' + o.data.postID).val(o.data.goods_amount);
                } else {
                    delete bill.generalGoods.general_data[this.postID];
                    $('#goods_line_' + o.data.postID).remove();
                }
                bill.global.total();

            } else {

                E.alert(o.message);

            }

        }

    },

    fittings: {

        data_array:{ },

        goods_index: 1,

        del_array : { },

        edit:function( id, k ){

            bill.generalGoods.fittings.del_array = { };

            bill.generalGoods.fittings.goods_index = k;

            var total_money = 0;

            var html = '<table class="table table-bordered">';
            html += '<tr>';
            html += '<th style="text-align: center">配件名称</th>';
            html += '<th style="text-align: center">单位</th>';
            html += '<th style="text-align: center">赠送数量</th>';
            html += '<th style="text-align: center">额外购买</th>';
            html += '</tr>';
          //mod by yim.hu FUN-BK-0009  配件价格 start


            $.each(bill.generalGoods.general_data[k].fittings,function(ke,va){

                if(va){
                    var del_str = '&nbsp;';
                    if(va.quantity > 0){
                        del_str += '<a href="javascript:void(0)" onclick="bill.generalGoods.fittings.del('+ ke +','+ k +')">删除</a>';
                    }

                    if(va.forsale > 0)
                        html += '<tr class="fittings_line-'+ k +' fit_'+ k + '_' +ke +'" can="1">';
                    else
                        html += '<tr class="fittings_line-'+ k +' fit_'+ k + '_' +ke +'" can="0">';

                    html += '<td style="text-align: center">'+ va.fitName +'</td>';
                    html += '<td style="text-align: center">'+ va.unitName +'</td>';
                    html += '<td style="text-align: center">'+ va.quantity + del_str +'</td>';

                    if(va.forsale > 0){
                    
                        html += '<td style="text-align: center">';
                        if(va.buyMoney>0){
                        	
                            html += '<input type="text"  class="form-control input-sm fittings_number" pre="'+ k +'" k="'+ ke +'"" style="width: 60px;display:inline-block" name="fittings_number" value="'+ va.buyNum +'" price="'+ va.buyMoney +'" />';
                        	
                        }else{                       	
                            html += '<input type="text"  class="form-control input-sm fittings_number" pre="'+ k +'" k="'+ ke +'"" style="width: 60px;display:inline-block" name="fittings_number" value="'+ va.buyNum +'" price="'+ va.price +'" />';
                        }
                        
                        	//假如是新增就不用管
                        	if(GetQueryString("operFlg")==3){
                        		
                        		if(va.buyMoney>0){
                            		html += '<span style="width:100px;display:inline-block;">&nbsp;&nbsp;'+ va.buyMoney +'元/'+ va.unitName +'</span>'; 

                        			
                        		}else if(va.buyMoney ==0){
                        		
                        			
                            		html += '<span style="width:100px;display:inline-block;">&nbsp;&nbsp;'+ Math.round(va.buyMoney*va.buyNum) +'元/'+ va.unitName +'</span>'; 

                        		}else{
                            		html += '<span style="width:100px;display:inline-block;">&nbsp;&nbsp;'+ va.price +'元/'+ va.unitName +'</span>'; 

                        		}
                        	}else{
                        		//这里还要做判断如果没单价就用默认的
                        		if(va.buyMoney>0){
                            		html += '<span style="width:100px;display:inline-block;">&nbsp;&nbsp;'+ va.buyMoney +'元/'+ va.unitName +'</span>'; 

                        			
                        		}else if(va.buyMoney ==0){
                        		
                        			
                            		html += '<span style="width:100px;display:inline-block;">&nbsp;&nbsp;'+ Math.round(va.buyMoney*va.buyNum) +'元/'+ va.unitName +'</span>'; 

                        		}else{
                            		html += '<span style="width:100px;display:inline-block;">&nbsp;&nbsp;'+ va.price +'元/'+ va.unitName +'</span>'; 

                        		}
                        	}

                        if(bill.args.isAuth == 1 ){//授权之后才会显示
                        	//假如是新增就不用管
                        	if(GetQueryString("operFlg")==3){
                        		if(va.buyMoney>=0){
                        			html += '小计<input type="text" value="'+Math.round(va.buyMoney*va.buyNum)+'" class="form-control input-sm fittings_number2 xiaoji" style="width: 40px;display:inline-block" /><span class="change_price"><a href="javascript:void(0)">修改</a></span></td>'
                        			
                        		}else{
                        			html += '小计<input type="text"  class="form-control input-sm fittings_number2 xiaoji" style="width: 40px;display:inline-block" /><span class="change_price"><a href="javascript:void(0)">修改</a></span></td>'
                        		}
                            	

                        	}else{
                        		
                        		
                        		html += '小计<input type="text" value="'+Math.ceil(va.buyMoney*va.buyNum)+'" class="form-control input-sm fittings_number2 xiaoji" style="width: 40px;display:inline-block" /><span class="change_price"><a href="javascript:void(0)">修改</a></span></td>'                        		

                        	}
                        	
                        }
                       // if(va.buyMoney>0){
                        	total_money += parseFloat(Math.ceil(va.buyNum * va.buyMoney));
                        	
                       // }else{
                       // 	total_money += parseFloat(va.buyNum * va.price);
                        	
                       // }
                       

                    }else{
                        html += '<td style="text-align: center"><span class="red">不可售</span></td>';
                    }
                    html += '</tr>';
                }

            });
            //mod by yim.hu FUN-BK-0009  配件价格 end
            html += '<tr><td colspan="5" style="text-align: center"><span class="red">配件总金额: <input type="text" class="form-control input-sm"  style="width: 100px;display: inline-block;" id="fittings_money_'+ k +'" name="fittings_money" value="'+ total_money.toFixed(2) +'" readonly></span></td></tr>';
            html += '</table>';
            E.popup.open({
                title: '修改配件',
                content: html,
                css: 'width: 700px',
                btnName:'修改配件',
                btnCall: 'bill.generalGoods.fittings.submit()'
            });

        },

        submit:function(){
        	//add by yim.hu FUN-BK-0009 修改配件 start
            var goods_index = bill.generalGoods.fittings.goods_index;
            var buyNum_str = '';
            var total_money = 0.00;
            var price_str = '';
            for(var i = 0; i < $(".fittings_line-" + goods_index).length; i++){

                var can = $(".fittings_line-" + goods_index).eq(i).attr('can');
                if(can > 0){
                	
                	//这里计算金额如果有小计就算小计的
                    
                    if($(".fittings_line-" + goods_index).eq(i).find('td').eq(0).html()=='额外餐具'){
                    	if(price1_xiaoji!=0){
                    		var price = price1_xiaoji/$(".fittings_line-" + goods_index).eq(i).find(".fittings_number").val();
                    	}else{
                    		var price = $(".fittings_line-" + goods_index).eq(i).find(".fittings_number").attr('price');
                    	}
                    }
                    if($(".fittings_line-" + goods_index).eq(i).find('td').eq(0).html()=='额外生日蜡烛'){
                    	if(price2_xiaoji!=0){
                    		var price =  price2_xiaoji/$(".fittings_line-" + goods_index).eq(i).find(".fittings_number").val();
                    		
                    	}else{
                    		var price = $(".fittings_line-" + goods_index).eq(i).find(".fittings_number").attr('price');
                    	}                   	
                    }
                    price = price+"";
                    price = price.substr(0,price.indexOf(".") + 3);
                    var buy_num = $(".fittings_line-" + goods_index).eq(i).find(".fittings_number").val();                 
                    if(!E.isInt(buy_num)){
                        buy_num = 0;
                    }

                    if(bill.generalGoods.general_data[goods_index].fittings[i] != undefined)
                    {
                        //console.log(i+" : " + buy_num);
                        bill.generalGoods.general_data[goods_index].fittings[i].buyNum = buy_num;
                        bill.generalGoods.general_data[goods_index].fittings[i].buyMoney = price;
                    }


                    


                }else{
                    buy_num = 0;
                    price = 0;
                }
                //console.log(bill.generalGoods.general_data[goods_index].fittings[i]);

                buyNum_str += buy_num+',';
                price_str +=  price+','
            }

            bill.generalGoods.general_data[goods_index].total_money = total_money.toFixed(2);

            E.ajax_post({
                url: '/invokingAjax-comm/bill/checkoutGoods.ajax?operFlg=7',
                data: {
                    buyNum:buyNum_str.substr(0,buyNum_str.length-1),
                    price:price_str.substr(0,price_str.length-1),
                    goods_index:bill.generalGoods.fittings.goods_index,
                    del_array: bill.generalGoods.fittings.del_array,
                    pcustID: bill.args.pcustID,
                    source: bill.args.source,
                    orders_code:bill.args.orders_code
                },
                call: 'bill.generalGoods.fittings.callBack'
            });
          //add by yim.hu FUN-BK-0009 修改配件 end
        },

        callBack:function( o ){

            if(o.code == 200 ){



                //更新代金卡
                bill.card.create(o.data);

                //检查商品促销活动、订单促销、计算金额
                bill.global.total();

                //删除配件
                $.each(bill.generalGoods.fittings.del_array,function(k, v){
                    delete bill.generalGoods.general_data[bill.generalGoods.fittings.goods_index].fittings[v];
                });

                E.popup.close();
            }else{
                E.alert(o.message);
            }
        },

        //删除配件
        del:function(index){

            var goods_index = bill.generalGoods.fittings.goods_index;
            bill.generalGoods.fittings.del_array[index] = index;
            $(".fit_"+goods_index+'_'+index).hide();

            var total_money = 0.00;
            var fittings_line = $(".fittings_line-"+goods_index);
            for(var i = 0; i < fittings_line.length; i++){

                if(fittings_line.eq(i).attr('can') > 0){
                    var buy_num = fittings_line.eq(i).find(".fittings_number").val();
                    var price = fittings_line.eq(i).find(".fittings_number").attr('price');

                    if(!E.isInt(buy_num)){
                        buy_num = 0;
                    }
                    var buy_money = parseFloat(buy_num*price);

                    total_money += buy_money;
                }
            }

            $("#fittings_money_"+goods_index).val(total_money.toFixed(2));

        }

    }

};


//代金卡类
bill.card = {

    card_array :{ },

    to_activate_num: 0,

    is_activate: 0,

    check: function( card_pwd ) {

        if (bill.args.total.total_amount == 0) {
            E.alert('请先添加商品');
            return false;
        }

        if (!card_pwd) {
            card_pwd = $("#card_pwd").val();
            this.is_activate = 0;
        } else {
            this.is_activate = 1;
        }

        var msg = '';

        if (E.empty(card_pwd)) {
            E.alert('请输入现金卡密码');
            return false;
        }

        if (bill.card.card_array[card_pwd]) {
            E.alert('现金卡已经使用，不可重复使用');
            $("#card_pwd").val('');
            return false;
        }

        E.loadding.open('正在努力加载中...');

        E.ajax_post({
            url: '/invokingAjax-comm/bill/checkout.ajax?operFlg=13',
            data: {
                card_pwd:card_pwd,
                bill_no: bill.args.bill_no,
                buy_log: bill.args.buy_log,
                source: bill.args.source,
                orders_code:bill.args.orders_code
            },
            call: "bill.card.result"
        });

    },

    create:function( o ){

        var html = '';

        if  (o) {
            var cardFlg = 0;
            $.each(o,function(k, v) {

                if(cardFlg == 0){
                    html += '<thead><tr>';
                    html += '<th width="150">现金卡名称</th>';
                    html += '<th width="150" class="tac">现金卡号</th>';
                    html += '<th width="120" class="tac">卡面值</th>';
                    html += '<th width="120" class="tac">抵扣金额</th>';
                    html += '<th width="100" class="tar">操作</th>';
                    html += '</tr></thead><tbody>';
                }

                bill.card.card_array[k] = k;
                html += '<tr id="card-goods-index-0">';
                html += '<td>'+ v.card_name +'</td>';
                html += '<td class="tac">'+ v.card_no +'</td>';
                html += '<td class="tac">'+ v.face_value +'</td>';
                html += '<td class="tac" ">'+ v.deducation +'</td>';
                html += '<td class="tar"><a href="javascript:void(0);" onclick="bill.card.del(\''+ v.card_pwd +'\')">取消</a></td>';
                html += '</tr>';

                cardFlg++;

            });

            if(cardFlg > 0){
                html += '</tbody>';
            }
        }
        $("#card_pwd").val('');
        $("#use_card_table").html(html);
    },

    result: function( o ) {

        E.loadding.close();

        if(o.code == 200 ){

            bill.card.card_array[o.data.card_pwd] = o.data.list;
            bill.card.create(o.data.list);

            if (this.is_activate) {
                $('#used_card_line_' + o.data.card_pwd).remove();
                this.to_activate_num--;
                if (this.to_activate_num == 0) {
                    $('#used_card_box').hide();
                }
            }

            //检查商品促销活动、订单促销、计算金额
            bill.global.total();

        } else {

            E.alert(o.message);

        }

    },

    del:function( card_pwd ){

        E.loadding.open('正在努力取消中...');

        E.ajax_post({
            url: '/invokingAjax-comm/bill/checkout.ajax?operFlg=14',
            data: {
                card_pwd:card_pwd,
                buy_log: bill.args.buy_log,
                source: bill.args.source,
                orders_code:bill.args.orders_code
            },
            call: "bill.card.delResult"
        });

    },

    delResult:function( o ){

        E.loadding.close();

        if(o.code == 200 ){

            delete bill.card.card_array[o.data.card_pwd];

            bill.card.create( o.data.list );

            //检查商品促销活动、订单促销、计算金额
            bill.global.total();

        }else{
            E.alert(o.message);
        }

    },

    cancel: function( card_pwd ) {
        $('#used_card_line_' + card_pwd).remove();
        this.to_activate_num--;
        if (this.to_activate_num == 0) {
            $('#used_card_box').hide();
        }
    }

}


//代付订单类
bill.paying_agent = {

    paying_agent_array : {},

    check:function(){

        var paying_agent_code = E.trim($("#paying_agent_code").val());

        if(E.isEmpty(paying_agent_code)){
            E.alert('请输入代付订单号');
            return false;
        }

        if(bill.paying_agent.paying_agent_array[paying_agent_code]){
            E.alert('代付订单不能重复');
            $("#paying_agent_code").val('');
            return false;
        }

        E.loadding.open('正在努力加载中...');

        E.ajax_post({
            url: '/invokingAjax-comm/bill/checkout.ajax?operFlg=15',
            data: {
                paying_agent_code:paying_agent_code,
                buy_log: bill.args.buy_log,
                source: bill.args.source,
                orders_code:bill.args.orders_code
            },
            call: function( o ) {

                E.loadding.close();
                if (o.code == 200) {

                    var paying_agent_code = o.data.bill_code;
                    bill.paying_agent.paying_agent_array[paying_agent_code] = 1;

                    var html = '';
                    $.each(o.data.list, function(k, v){
                        html += '<tr id="paying_agent_' + v.bill_code + '">';
                        html += '<td>'+ v.bill_code +'</td>';
                        html += '<td class="tac">'+ v.deliver_name +'</td>';
                        html += '<td class="tac">'+ v.bill_receivable_money +'</td>';
                        html += '<td class="tac"><a href="javascript:void(0);" onclick="bill.paying_agent.cancel(\''+ v.bill_code +'\')">取消</a></td>';
                        html += '</tr>';

                    });

                    //计算活动、金额
                    bill.global.total();

                    $('#paying_agent_code').val('');
                    $('#paying_agent_list').html(html);

                } else {
                    E.alert(o.message);
                }

            }

        });

    },

    cancel: function( bill_code ){

        E.loadding.open('正在努力取消中...');

        E.ajax_post({
            url: '/invokingAjax-comm/bill/checkout.ajax?operFlg=16',
            data: {
                paying_agent_code: bill_code,
                buy_log: bill.args.buy_log,
                source: bill.args.source,
                orders_code:bill.args.orders_code
            },
            call: function( o ) {

                E.loadding.close();
                if(o.code == 200){

                    var paying_agent_code = o.data;

                    delete bill.paying_agent.paying_agent_array[paying_agent_code];

                    $('#paying_agent_' + paying_agent_code).remove();

                    //计算活动、金额
                    bill.global.total();

                } else {
                    E.alert(o.message);
                }

            }
        });
    }

}


//使用余额类
bill.balance = {

    is_use: 0,

    check:function(){

        if(bill.balance.is_use == 1){

            E.ajax_post({
                url: '/invokingAjax-comm/bill/checkout.ajax?operFlg=20',
                data: {
                    buy_log: bill.args.buy_log,
                    source: bill.args.source,
                    orders_code:bill.args.orders_code
                },
                call: "bill.balance.cancelResult"
            });

        }else{

            var balance_money = $.trim($("#balance_number").val());

            if(E.isEmpty(balance_money)){
                E.alert('请输入余额');
                return false;
            }

            if(!E.isMoney(balance_money)){
                E.alert('输入的金额不正确，请重新输入');
                return false;
            }

            E.ajax_post({
                url: '/invokingAjax-comm/bill/checkout.ajax?operFlg=19',
                data: {
                    balance:balance_money,
                    buy_log: bill.args.buy_log,
                    source: bill.args.source,
                    orders_code:bill.args.orders_code
                },
                call: "bill.balance.useResult"
            });

        }

    },

    useResult:function( o ){

        if(o.code == 200){

            var balance = o.data.balance;

            bill.balance.is_use = 1;
            $("#balance_number").attr('disabled',true);
            $("#use_balance").text('取消使用');

            E.alert('余额使用成功',2);
            //计算金额
            bill.global.total();

        }else{
            E.alert(o.message);
        }

    },

    cancelResult:function( o ){

        if(o.code == 200){

            bill.balance.is_use = 0;

            $("#balance_number").val('').attr('disabled', false);
            $("#use_balance").text('使用');

            //计算金额
            bill.global.total();

        }else{

            E.alert(o.message);
        }

    }

}


//优惠券类
bill.coupon = {

    //已经使用优惠券数组
    use_coupon_array : { },

    //使用优惠券
    useCoupon:function(){

        var coupon_code = $("#coupon_code").val();

        if(E.isEmpty(coupon_code)){
            E.alert('请输入优惠券编号');
            return false;
        }

        if(bill.coupon.use_coupon_array[coupon_code]){
            E.alert('已经使用了这个优惠，不可重复使用');
            return false;
        }

        E.ajax_post({
            url: '/invokingAjax-comm/bill/checkout.ajax?operFlg=7',
            data: {
                code: coupon_code,
                buy_log: bill.args.buy_log,
                source: bill.args.source,
                orders_code:bill.args.orders_code
            },
            call: function( result_data ) {

                if (result_data.code == 200) {

                    bill.coupon.use_coupon_array[result_data.data.code] = result_data.data.code;
                    bill.coupon.createUseCouponList();
                    $('#coupon_code').val('');
                    bill.global.total();
                    E.alert('优惠券使用成功',2);

                } else {
                    $('#coupon_code').val('');
                    E.alert(result_data.message);

                }
            }
        });

    },

    //取消使用优惠券
    cancelUseCoupon:function( code ){

        if(E.isEmpty(code)){
            E.alert('取消优惠券编码不能为空');
            return false;
        }

        E.ajax_post({
            url: '/invokingAjax-comm/bill/checkout.ajax?operFlg=8',
            data: {
                code: code,
                buy_log: bill.args.buy_log,
                source: bill.args.source,
                orders_code:bill.args.orders_code
            },
            call: function( result_data ) {

                if (result_data.code == 200) {

                    E.alert('优惠券取消成功',2);

                    delete bill.coupon.use_coupon_array[result_data.data];
                    bill.coupon.createUseCouponList();
                    $('#coupon_code').val('');
                    bill.global.total();

                } else {

                    $('#coupon_code').val('');
                    E.alert(result_data.message);

                }
            }
        });

    },

    //优惠券列表
    createUseCouponList:function(){

        var result_data = bill.coupon.use_coupon_array;

        var countFlg = 0;
        var html = '';
        $.each(result_data,function(k, v){

            if(countFlg==0){
                html = '<table class="table" style="width: 300px;">';
                html += '<tr class="active"><th>编号</th><th class="tac">操作</th></tr>';
            }

            html += '<tr><td style="height: 30px;line-height: 30px;">'+ v +'</td><td class="tac"><button type="button" class="btn btn-danger btn-sm" onclick="bill.coupon.cancelUseCoupon(\''+ v +'\')" >取消使用</button></td></tr>';
            countFlg++;

        })

        if(countFlg > 0){
            html += '</table>';
        }

        $("#has_use_coupon").empty().html(html);

    }

};


//检查促销渠道类
bill.promotionChannel = {

    promotionChannel_data : '',

    check:function(){

        E.loadding.open("正在加载商品，请稍等...");

        bill.promotionChannel.promotionChannel_data = $("#billPromotion").val();

        E.ajax_post({
            url: '/invokingAjax-comm/bill/checkout.ajax?operFlg=10',
            data: {
                pcustID: bill.args.pcustID,
                buy_log:bill.args.buy_log,
                billPromotion:bill.promotionChannel.promotionChannel_data,
                source: bill.args.source,
                orders_code:bill.args.orders_code
            },
            call: "bill.common.result"
        });
    },

    result:function( o ){

        E.loadding.close();
        if(o.code == 200){

            //更新现金卡
            bill.card.create(o.data.card_array);

            //检查商品促销活动、订单促销、计算金额
            bill.global.total();

        }else{
            E.alert(o.message);
        }
    }

}


bill.common = {

    result:function(o){

        E.loadding.close();
        if(o.code == 200){

            //检查商品促销活动、订单促销、计算金额
            bill.global.total();

        }else{
            E.alert(o.message);
        }
    }
}

//客服授权类
bill.serviceAccredit = {

    check:function(){
        html = '<form class="form-horizontal" role="form">';
        html += '<div class="form-group">';
        html += '<label for="auth_username" class="col-sm-2 control-label">用户名</label>';
        html += '<div class="col-sm-10">';
        html += '<input type="text" class="form-control" id="auth_username" placeholder="请输入用户名"></div>';
        html += '</div>';
        html += '<div class="form-group">';
        html += '<label for="auth_password" class="col-sm-2 control-label">密码</label>';
        html += '<div class="col-sm-10">';
        html += '<input type="password" class="form-control" id="auth_password" placeholder="请输入密码"></div>';
        html += '</div>';
        html += '</form>';

        E.popup.open({
            title: '授权操作',
            content: html,
            css: 'width: 450px;',
            btnName: '授权',
            btnCall: "bill.serviceAccredit.execute();"
        });

    },

    execute:function(){

        var username = $("#auth_username").val();
        var pwd = $("#auth_password").val();

        E.ajax_post({
            url: '/invokingAjax-comm/bill/checkout.ajax?operFlg=17',
            data: {
                userID:username,
                userPwd:pwd,
                code:bill.args.code,
                buy_log:bill.args.buy_log,
                pcustID: bill.args.pcustID,
                source: bill.args.source,
                orders_code:bill.args.orders_code
            },
            call: 'bill.serviceAccredit.callBack'
        });

    },

    callBack:function( o ){

        if(o.code == 200){

            bill.args.isAuth = 1;

            $(".freight_noAuth").hide();
            $(".freight_isAuth").show();
            $("#btn_auth").remove();
            $(".authPrice").show();

            E.alert('授权成功',2);
            E.popup.close();

        }else{
            E.alert(o.message );
        }

    }

}


//检查配送时间类
bill.checkDeliveryTime = {

    check: function() {

        var send_date = $('#send_date').val(),
            start_time = $('#start_time').val(),
            end_time = $('#end_time').val(),
            msg = '';
        var billType=$("#billType").val();//获取订单类型
        /*
         * 获取服务器当前日期 时间 start
         */
        var date=new Date($.ajax({async:false}).getResponseHeader("Date"));
        //alert(date);
        var year=date.getFullYear();//年
        var month= (date.getMonth()+1*1)<10 ? '0'+(date.getMonth()+1*1) : (date.getMonth()+1*1);//月
        var day=(date.getDate())<10 ? '0'+(date.getDate()) :(date.getDate());//日
        var hours= (date.getHours())<10 ? '0'+(date.getHours()) : (date.getHours());//时
        var minutes= (date.getMinutes())<10 ? '0'+(date.getMinutes()) : (date.getMinutes());//时
        var seconds= (date.getSeconds())<10 ? '0'+(date.getSeconds()) : (date.getSeconds());//时
        var dateTime=year+""+month+""+day; //日期 格式 20140901
        var time=hours+""+minutes+""+seconds;//时间 格式140536
        //add yim.hu 20141128 FUN-BK-0036 新增订单爆单提示 --start
        	//先把配送开始 与结束时间放到隐藏input中方便读取
        	$('#hidden_start_time').val(start_time);
        	$('#hidden_end_time').val(end_time);
        	//根据有没有逗号判断一下如果不是爆单那么提示文字隐藏
        	
        	if(start_time.indexOf(',')>0){
        		
        		start_time = start_time.substring(0,8);
        	
        		$('#tishi_baodan').show();
        		
        	}else{
        		
        		$('#tishi_baodan').hide();
        		
        	}
        	
        //add yim.hu 20141128 FUN-BK-0036 新增订单爆单提示 --end
        //选择的配送日期字符串
        var senDate=send_date.replace(/\-/gi,'');
        //开始时间字符串
        var startTime=start_time.replace(/\:/gi,'');

        /*
         * 获取当前日期 时间 end
         */

        //订单类型为试吃订单
        if(billType==9){
                if(senDate<dateTime){
                    msg += '配送日期不能小于当前日期<br/>';
                }else if(senDate==dateTime && !E.isEmpty(start_time)){
                    if(startTime<time)
                        msg += '配送时间不能小于当前时间<br/>';
                }
        }

        if (E.isEmpty(send_date)) {
            msg += '配送日期不能为空<br/>';
        }

        if (E.isEmpty(start_time)) {
            msg += '配送开始时间必须选择<br/>';
        }

        if (!E.isEmpty(end_time) && start_time > end_time) {
            msg += '配送结束时间必须大于配送开始时间<br/>';
        }

        if(!E.isEmpty(msg)){
            E.alert(msg);
            return false;
        }

        E.loadding.open('正在努力加载中...');

        E.ajax_post({
            url: '/invokingAjax-comm/bill/checkoutGoods.ajax?operFlg=6',
            data: {
                pcustID: bill.args.pcustID,
                send_date: send_date,
                send_start_time: start_time,
                send_end_time: end_time,
                source: bill.args.source,
                orders_code:bill.args.orders_code
            },
            call: "bill.checkDeliveryTime.result"
        });

    },

    result:function(o){

        E.loadding.close();

        if (o.code == 200) {
            bill.global.isDeliveryTime = 1;
            var html = '配送日期：'+ o.data.send_date +'&nbsp;&nbsp;&nbsp;开始配送时间：'+ o.data.send_start_time +'&nbsp;&nbsp;&nbsp;时间段结束时间：'+ o.data.send_end_time+'&nbsp;&nbsp;<button type="button" onclick="bill.checkDeliveryTime.up()" class="btn btn-default">修改</button>';
            $('#send_time_text').html( html).show();
            $('#send_time_box').hide();

            //检查商品促销活动、订单促销、计算金额
            bill.global.total();

        }else{
            E.alert(o.message);
        }
    },

    up:function(){
        bill.global.isDeliveryTime = 0;
        $('#send_time_text').hide();
        $('#send_time_box').show();
    }

}

//修改运费类
bill.upFreight = {

    is_up:0,

    check:function(){

        if(bill.upFreight.is_up == 1){

            bill.upFreight.is_up = 0;
            $("#alterFreight").attr('disabled',false);

        }else{

            var alterFreight = $("#alterFreight").val();

            if(alterFreight != ''){
                if(!E.isMoney(alterFreight)){
                    E.alert('输入的金额不正确');
                    $("#alterFreight").val('');
                    return false;
                }
            }

            E.ajax_post({
                url: '/invokingAjax-comm/bill/checkout.ajax?operFlg=18',
                data: {
                    alterFreight:alterFreight,
                    code:bill.args.code,
                    pcustID: bill.args.pcustID,
                    buy_log:bill.args.buy_log,
                    source: bill.args.source,
                    orders_code:bill.args.orders_code
                },
                call: "bill.upFreight.result"
            });
        }

    },

    result:function( o ){
        if(o.code == 200){

            bill.upFreight.is_up = 1;
            $("#alterFreight").attr('disabled',true);
            bill.global.total();

        }else{
            E.alert(o.message);
        }
    }

}

//使用积分
bill.points = {

    is_use:0,

    use:function(){

        var points = $("#points_number").val();
        E.ajax_post({
            url:'/invokingAjax-comm/bill/checkout.ajax?operFlg=11',
            data:{
                points: points,
                buy_log: bill.args.buy_log,
                source: bill.args.source,
                orders_code:bill.args.orders_code
            },
            call:'bill.points.use_result'
        });
    },

    use_result:function( o ){

        if(o.code == 200){

            $("#points_number").val(o.data.bill_points_money).attr('disabled',true);
            $("#use_points").text('取消');
            $("#use_points").attr('id','cancel_points');

            E.alert('积分使用成功',2);
            bill.global.total();

        } else {
            $("#points_number").val('');
            E.alert(o.message);
        }

    },

    cancel:function(){

        var points = $("#points_number").val();
        E.ajax_post({
            url:'/invokingAjax-comm/bill/checkout.ajax?operFlg=12',
            data:{
                points: points,
                buy_log: bill.args.buy_log,
                source: bill.args.source,
                orders_code:bill.args.orders_code
            },
            call:'bill.points.cancel_result'
        });
    },

    cancel_result:function( o ){

        if(o.code == 200){
            $("#points_number").val('').attr('disabled',false);
            $("#cancel_points").text('使用');
            $("#cancel_points").attr('id','use_points');
            bill.global.total();
        }else{
            $("#points_number").val('');
            E.alert(o.message);
        }
    }

}


//调价类
bill.adjustPrice = {

    check:function( index ){

        var adjustPrice = '';
        if(bill.generalGoods.general_data[index]['adjustPrice'] >= 0){
            adjustPrice = bill.generalGoods.general_data[index]['adjustPrice'];
        }

        var price = parseFloat($("#goods_"+index).find(".price span").text());

        html = '<form class="form-horizontal" role="form">';
        html += '<div class="form-group">';
        html += '<label class="col-sm-2 control-label">售价</label>';
        html += '<div class="col-sm-10">'+ price.toFixed(2) +'</div>';
        html += '</div>';
        html += '<div class="form-group">';
        html += '<label for="adjustPrice_'+ index +'" class="col-sm-2 control-label">调价</label>';
        html += '<div class="col-sm-10">';
        html += '<input type="text" class="form-control" value="'+ adjustPrice +'" id="adjustPrice_'+ index +'" placeholder="请输入调价金额"></div>';
        html += '</div>';
        html += '</form>';

        E.popup.open({
            title: '手动调价',
            content: html,
            css: 'width: 360px;',
            btnName: '确定',
            btnCall: "bill.adjustPrice.execute("+ index +");"
        });

    },

    execute:function(index){

        var adjustPrice = $("#adjustPrice_"+index).val();

        if(!E.isMoney(adjustPrice) && !E.empty(adjustPrice)){
            E.alert('输入的金额不正确');
            return false;
        }

        E.ajax_post({
            url: '/invokingAjax-comm/bill/checkoutGoods.ajax?operFlg=8',
            data: {
                adjustPrice:adjustPrice,
                goods_index:index,
                code:bill.args.code,
                buy_log:bill.args.buy_log,
                pcustID: bill.args.pcustID,
                source: bill.args.source,
                orders_code:bill.args.orders_code
            },
            call: 'bill.adjustPrice.callBack'
        });
    },

    callBack:function( o ){

        E.popup.close();
        if(o.code == 200){

            if(o.data.goods_index){
                var goods_index = o.data.goods_index;
                var adjustPrice = o.data.adjustPrice;
                bill.generalGoods.general_data[goods_index]['adjustPrice'] = adjustPrice;
                bill.generalGoods.general_data[goods_index]['price'] = adjustPrice;
               
            }
           
            //更新代金卡
            bill.card.create(o.data.card_array );

            //检查商品促销活动、订单促销、计算金额
            bill.global.total();

        }else{
            E.alert(o.message);
        }

    }

}

//地图类
bill.map = {

    open:function(id){

        var html = '<div id="address_map" style="width: 778px;height: 390px"></div>';
        var deliver_array = bill.deliver.d_data[id];

        E.popup.open({
            title: '查看地图',
            content:html,
            css: 'width:800px'
        });

        mapMarker.M_address = deliver_array.address;
        mapMarker.M_city = deliver_array.cityName;
        mapMarker.M_type = 1;
        map.city_name = deliver_array.cityName;
        map.G_id = 'address_map';
        map.G_cityid = deliver_array.cityid;
        map.G_zoom = 10;
        //del 20141124 sunqiang  FUN-BK-0034 运费规则调整 start
        //map.G_type = 2;
        //del 20141124 sunqiang  FUN-BK-0034 运费规则调整 end
        //add allen.qiang 20141204 FUN-BK-0041-G7地址库平台接入---start
        map.longitude=deliver_array.longitude;
        map.latitude=deliver_array.latitude;
        //add allen.qiang 20141204 FUN-BK-0041-G7地址库平台接入---end
        map.setMap();
        mapArea.search();
    }

}


//地图区域
var mapArea = {

    areaBox: {},

    checkedBox: {},

    pathOverlay: function( area_obj ) {

        //设置多边形样式
        var polygon = new BMap.Polygon();
        polygon.setPath( area_obj.path );
        polygon.setStrokeColor(area_obj.colour);
        polygon.setFillColor(area_obj.colour);
        polygon.setStrokeOpacity(0.8);
        polygon.setFillOpacity(0.6);
        polygon.setStrokeWeight(1);
        polygon.setStrokeStyle('solid');
        map.G_map.addOverlay(polygon);

    },

    search:function(){
        E.ajax_get({
            url:'/invokingAjax-backend/system/mapAreaZoning.ajax?operFlg=1',
            data: {
                cityID:map.G_cityid,
                brandID:82
            },
            call: 'mapArea.result'
        });
    },

    result:function(o){

        map.G_map.clearOverlays();

        if (o.code == 200) {

            $.each(o.data, function(k, v) {

                //运费
                if(k == map.G_type){

                    $.each(v, function(i, j) {

                        var points_array = new Array();

                        $.each(j.path, function(x, y) {
                            points_array[x] = {
                                //mod by allen.qiang 20150422 坐标数据类似改为 浮点数 --start
                                lat: parseFloat(y.latitude),
                                lng: parseFloat(y.longitude)
                                //mod by allen.qiang 20150422 坐标数据类似改为 浮点数 --end
                            };

                        });

                        mapArea.areaBox[j.areaID] = {
                            path: points_array,
                            colour: j.colour,
                            areaID: j.areaID,
                            areaName: j.areaName,
                            type: j.type,
                            areaCode: j.areaCode
                        };
                        mapArea.checkedBox[j.areaID] = 1;

                        if (mapArea.checkedBox[j.areaID]) {
                            mapArea.pathOverlay( mapArea.areaBox[j.areaID] );
                        }
                    });
                }

            });

            if(mapMarker.M_type == 1){
                mapMarker.setMarker();
            }

        }
    }

}

/**
 * 设置标点覆盖物类
 * @type {{M_marker: {}, M_address: string, M_city: string, M_zoom: number, setMarker: Function}}
 * 根据地理位置获取和设置
 */
var mapMarker = {

    M_marker:{ },

    M_address:'',

    M_city:'',

    M_zoom: 14,

    M_type:0,

    setMarker:function(){

//        map.G_map.clearOverlays();

        mapMarker.M_marker = new BMap.Geocoder();

        //mod allen.qiang 20141204 FUN-BK-0041-G7地址库平台接入---start
        if(map.longitude==""||map.latitude==""||map.longitude==null||map.latitude==null){ //如果地址的经纬度没有则调用百度
            // 将地址解析结果显示在地图上,并调整地图视野
            mapMarker.M_marker.getPoint(mapMarker.M_address, function(point){
                if (point) {
                    map.G_map.centerAndZoom(point, mapMarker.M_zoom);
                    map.G_map.addOverlay(new BMap.Marker(point));
                }
            }, mapMarker.M_city);
        }else{
            var point = new BMap.Point(map.longitude, map.latitude);//定义一个中心点坐标
            map.G_map.centerAndZoom(point, mapMarker.M_zoom);
            map.G_map.addOverlay(new BMap.Marker(point));
        }
        //mod allen.qiang 20141204 FUN-BK-0041-G7地址库平台接入---end
    }

}


//地图设置类
var map = {

    G_map:{},

    city_name:'',

    G_zoom:14,

    //区域类型：1、配送站 2、运费
    //mod 20141124 sunqiang  FUN-BK-0034 运费规则调整 start
    G_type : 1,
    //G_type:2,
    //mod 20141124 sunqiang  FUN-BK-0034 运费规则调整 end
    //id
    G_id:'',

    G_cityid:0,

    //add allen.qiang 20141204 FUN-BK-0041-G7地址库平台接入---start
    longitude:'',
    latitude:'',
    //mod allen.qiang 20141204 FUN-BK-0041-G7地址库平台接入---end

    setMap:function(){
        map.G_map = new BMap.Map(map.G_id, {enableMapClick:false}),  // 创建Map实例

        map.G_map.enableScrollWheelZoom();                                   //启动鼠标滚轮操作
        map.G_map.disableDoubleClickZoom();                                   //禁用双击放大
        map.G_map.addControl(new BMap.NavigationControl());                  //添加默认缩放平移控件

        //移动地图中心点
        map.G_map.centerAndZoom(map.city_name, map.G_zoom);
    }
}


//事件处理类
var Event = {

    billType:{

        confirm:function(){

            var cityID = $("#billCity").val();
            var billType  = $("#billType").val();
            var bill_no = bill.args.bill_no;
            var operateType = $("#operateType").val();
            if(!E.empty(bill_no)){

                var url = "/quanliadmin/app/bill/billEdit.pscript?operFlg=1&bill_no="+ bill.args.bill_no +"&bill_type="+billType;

            }else{
                if(operateType){
                var url = "/quanliadmin/app/bill/billEdit.pscript?operFlg=3&operateType="+operateType+"&pcustID="+bill.args.pcustID+"&cityid="+cityID+"&bill_type="+billType;
            }else{
                var url = "/quanliadmin/app/bill/billEdit.pscript?operFlg=3&pcustID="+bill.args.pcustID+"&cityid="+cityID+"&bill_type="+billType;
                }
            }
            self.location = url;
        },

        cancal:function(){

            var billType  = $("#billType").val();
            if(billType != bill.args.preBillType){

                $("#billType").val(bill.args.preBillType);

            }
        }
    }

}

$(window).ready(function() {

    //修改运费
    $(document).on("change",'#update_freight',function(){
        //修改的运费
        var update_freight = parseFloat($(this).val());
        //实收总金额
        var total_reality_money = parseFloat($("#total_reality_money").text());
        var total_receivable_money = update_freight+total_reality_money;

        if(!E.isMoney(update_freight)){
            E.alert('请填写正确的金额');
            $("#freight").val('');
            update_freight = bill.args.total.freight;
            total_receivable_money = bill.args.total.total_receivable_money;
        }

        $("#freight").text(update_freight.toFixed(2));
        $("#total_receivable_money").text(total_receivable_money.toFixed(2));

    });

    //用户未使用优惠券选择
    $(document).on('click','.coupon_choose',function(){
        var code = $(this).attr('code');
        $("#coupon_code").val(code);
    });
    //mod by yim.hu FUN-BK-0009  修改配件额外购买个数 start
    $(document).on('keyup','.fittings_number',function(){
    	
        var goods_index = bill.generalGoods.fittings.goods_index;
        var total_money = 0.00;

        for(var i = 0; i < $(".fittings_line-" + goods_index).length; i++){
            var can = $(".fittings_line-" + goods_index).eq(i).attr('can');
            
          
            if(can > 0){
            	$(".fittings_line-" + goods_index).find('td').eq(0).text()
                var price = $(".fittings_line-" + goods_index).eq(i).find(".fittings_number").attr('price');
       
                var buy_num = $(".fittings_line-" + goods_index).eq(i).find(".fittings_number").val();
                if($(".fittings_line-" + goods_index).eq(i).find('td').eq(0).text()=='额外餐具'){
                	price1_xiaoji = Math.ceil(price*buy_num);                	
                }
                if($(".fittings_line-" + goods_index).eq(i).find('td').eq(0).text()=='额外生日蜡烛'){
                	price2_xiaoji = Math.ceil(price*buy_num);                	
                }
                
               
                $(".fittings_line-" + goods_index).eq(i).find(".fittings_number2").val(Math.ceil(price*buy_num));
                if(!E.isInt(buy_num)){
                    buy_num = 0;
                }
                buy_num = parseInt(buy_num);
                total_money += Math.ceil(price*buy_num);
            }
            
            
        }
        
        $("#fittings_money_"+goods_index).val(parseFloat(total_money).toFixed(2));

    })
    //mod by yim.hu FUN-BK-0009  修改配件额外购买个数 end
    $(document).on('click','#use_points',function(){

        var deduction_money = $("#points_number").val();

        if(E.isEmpty(deduction_money)){
            E.alert('请输入抵扣的金额');
            return false;
        }

        if(deduction_money == 0 || deduction_money == '0'){
            E.alert('请输入抵扣的金额不能为0');
            $("#points_number").val('');
            return false;
        }

        if(parseInt(deduction_money) != deduction_money){
            E.alert('输入金额必须为正整数');
            $("#points_number").val('');
            return false;
        }

        if(!E.isMoney(deduction_money)){
            E.alert('输入的金额不正确，请重新输入');
            $("#points_number").val('');
            return false;
        }

        bill.points.use();

    });

    $(document).on('click',"#cancel_points",function(){
        bill.points.cancel();
    })

    $('#goods_code').on({
        keypress: function(event) {
        
            if (event.keyCode == '13') {
                event.preventDefault();
                var goods_code = E.trim($(this).val());

                if (E.isEmpty(goods_code)) {
                    E.alert('请输入商品编号');
                    return false;
                }
                bill.generalGoods.detail.search([{ product_code: goods_code, amount: 1 }]);
                

            }
        }
    });

    $('#goods_name').on({
        keypress: function(event) {
        	
            if (event.keyCode == '13') {
                event.preventDefault();
                var goods_name = E.trim($(this).val());
                if (E.isEmpty(goods_name)) {
                    E.alert('请输入商品名称');
                    return false;
                }
                bill.generalGoods.list.search('', goods_name);
            }
        }

    });

    $(document).on('click', 'a.delete_goods', function() {

        var data = $(this).attr('ebsig-data').split(',');

        if (data[1] == 'general') {
            bill.generalGoods.del.open( data[0] );
        }
    });

    $(document).on('click', 'a.icon_reduce', function() {
        var data = $(this).attr('ebsig-data'),
            data_array = data.split(','),
            goods_amount = parseInt($('#goods_amount_' + data_array[0]).val());
        if (data_array[1] == 'general') {
            if (goods_amount-1 == 0) {
                bill.generalGoods.del.open( data_array[0] );
            } else {
                bill.generalGoods.update.execute( data_array[0], -1 );
            }
        }
    });

    $(document).on('click', 'a.icon_subjoin', function() {
        var data = $(this).attr('ebsig-data'),
            data_array = data.split(',');
        if (data_array[1] == 'general') {
            bill.generalGoods.update.execute( data_array[0], 1 );
        }
    });

    $('#use_coupon').on('click', function() {
        bill.coupon.use();
    });

    //配送日期
    $(document).on('change','#goodsDate',function(){
        var start_date = $.trim($(this).val());
        $("#start_time").val('');
        $("#end_time").val('');
        if(start_date < bill.generalGoods.goods_time.start_date){
            $(this).val(bill.generalGoods.goods_time.start_date);
            return;
        }

        if(start_date > bill.generalGoods.goods_time.start_date){
            $("#start_time").find("option").attr('disabled',false);
            $("#end_time").find("option").attr('disabled',false);
            return;
        }

        if(start_date == bill.generalGoods.goods_time.start_date){

            var start_obj = $("#start_time").find('option');
            var end_obj = $("#end_time").find('option');
            var start_time = '';

            var end_time = bill.generalGoods.goods_time.end_time;
            if(!E.empty(bill.generalGoods.goods_time.cutTime)){
                end_time = bill.generalGoods.goods_time.cutTime;
            }
            var start_time = bill.generalGoods.goods_time.start_time
            $.each(start_obj,function(k,v){
                var time = $.trim($(this).html());

                if(time < start_time){
                    $(this).attr('disabled',true);
                }

                if(time > end_time){
                    $(this).attr('disabled',true);
                }

            });
            $.each(end_obj,function(k,v){

                var time = $.trim($(this).html());
                if(time <= start_time){
                    $(this).attr('disabled',true);
                }

                if(time > end_time){
                    $(this).attr('disabled',true);
                }
            });

        }
    });

    //添加生日牌
    $(document).on('change','.birthcard-select',function(){
        var select_str = $.trim($(this).find("option:selected").text());
        if(select_str == '请选择生日牌'){
            return false;
        }
        $(this).siblings('input[name="birthcard"]').val(select_str);
    });

    //添加切分
    $(document).on('change','.syncopate-select',function(){
        var select_str = $.trim($(this).find("option:selected").text());
        $(this).siblings('input[name="syncopate"]').val(select_str);
    });

    //城市更改
    $("#billCity").focus(function(){
        bill.preCityId = $("#billCity option:selected").val();
    });

    /**
     * 订单类型改变事件，主要为试吃订单事件改变
     */
    $(document).on('change','#billType',function(){
        var billType  = $("#billType").val();
        bill.args.billType = billType;
        if (Object.keys(bill.generalGoods.general_data).length == 0) {
            if(billType == 2 || billType == 3 || billType == 5 || billType == 7 || billType == 9 || bill.args.preBillType == 9){
                Event.billType.confirm();
            }
            bill.args.preBillType = billType;
        }else{

            if(billType == 2 || billType == 3 || billType == 5 || billType == 7 || billType == 9 || bill.args.preBillType == 9){
                if(E.empty(bill.args.bill_no)){
                    E.confirm("您确定切订单类型，如果是将清空您所填的所有信息！", "Event.billType.confirm", "Event.billType.cancal");
                }else{
                    E.confirm("您确定切订单类型，如果是可能会清空你部分信息！", "Event.billType.confirm", "Event.billType.cancal");
                }
            }else{
                bill.args.preBillType = billType;
            }
//          订单应收为0
        	if(t==9 || t==2 || t==3 || t==5 || t==7){

                if(billType==1 || billType ==4 || billType ==6 || billType==8){
                    if(E.empty(bill.args.bill_no)){
                        E.confirm("您确定切订单类型，如果是将清空您所填的所有信息！", "Event.billType.confirm", "Event.billType.cancal");
                    }else{
                        E.confirm("您确定切订单类型，如果是可能会清空你部分信息！", "Event.billType.confirm", "Event.billType.cancal");
                    }

                }

            }else {
                if(billType == 9 || bill.args.preBillType == 9 || billType==2 || billType==7 || billType==5 || billType==3){
                    if(E.empty(bill.args.bill_no)){
                        E.confirm("您确定切订单类型，如果是将清空您所填的所有信息！", "Event.billType.confirm", "Event.billType.cancal");
                    }else{
                        E.confirm("您确定切订单类型，如果是可能会清空你部分信息！", "Event.billType.confirm", "Event.billType.cancal");
                    }
                }else{
                    bill.args.preBillType = billType;
                }

            }

        }
    });

    $(document).on('change','#billCity',function(){

        bill.cityId = $("#billCity").val();

        if (Object.keys(bill.generalGoods.general_data).length == 0) {

            bill.city_confirm();
        }else{
            E.confirm("您确定切换城市吗，如果是将清空您所填的所有信息！", "bill.city_confirm", "bill.city_cancal");

        }
    });

    //促销渠道
    $("#billPromotion").change(function(){
        var promotionChannelID = $("#billPlace").val();
        bill.promotionChannel.promotionChannel_data.promotionChannelID = promotionChannelID;
        bill.promotionChannel.check();
    });
    //add by yim.hu FUN-BK-0009  配单价格修改 start
    $(document).on('click','.change_price',function(){
    	var this_p = $(this).parent();//先获取父级
    	 goods_index = bill.generalGoods.fittings.goods_index;
    	//获取当前的数量
    	var n1 =  this_p.children('input').eq(0).val();


    	//获取当前的价格
    	var p1 = this_p.children('input').eq(1).val();
    	//做判断是否为整数 如果不是整数就清空
    	if(p1%1 != 0 || p1 =='' ){
    		alert('小计请填写整数');
    		return false;
    	}
    	if(n1%1 != 0 || n1 =='' || n1=='0'){
    		alert('数量请填写整数');
    		return false;   		
    		
    	}
    	//1.00元/套 换成我们现在的价格除以数量并且小数点为2位
    	 	var s = p1/n1+"";
    	 	
    	    var str_s = s.substr(0,s.indexOf(".") + 3);
    	 
    	this_p.children('span').eq(0).html(str_s+"元/套");
    	//如果使用过小计那么这里小计就为1
    	xiaoji = 1;
    	var price = 0;
    	var price_total = 0;
    	var buyNum_str ='';
    	var price_str = '';
    	this_p.find(".fittings_number").attr('price',(p1/n1));
    	//接下来就是显示价格
        for(var i = 0; i <= $(".fittings_line-"+goods_index).length; i++){
        	  
            var can = $(".fittings_line-"+goods_index).eq(i).attr('can');
          
            if(can > 0){
            	
            	//这里计算金额如果有小计就算小计的
            	
                 price = parseFloat($(".fittings_line-"+goods_index).eq(i).find(".xiaoji").val());
              
                 if(price>0){
                	 //每次都要判断数字是否有
                	 if($(".fittings_line-"+goods_index).eq(i).find('.fittings_number').val()==0){
                		 alert('请填写数量');
                		 return false;
                	 }
                	 price = price;
                 }else{
                	 price = 0;
                 }
                 if($(".fittings_line-"+goods_index).eq(i).children('td').eq(0).html()=='额外餐具'){
                	 
                		 price1_xiaoji = price;
                
                 } 
                 if($(".fittings_line-"+goods_index).eq(i).children('td').eq(0).html()=='额外生日蜡烛'){
                	
                		 price2_xiaoji = price;
       
                	
                 }
                 price_total+=price;
                 var buy_num = $(".fittings_line-"+goods_index).eq(i).find(".fittings_number").val();  
                
            }else{
                buy_num = 0;
                price = 0;
            }
            buyNum_str += buy_num+',';
            price_str +=  price+','
        }
     
        $('#fittings_money_'+goods_index).val(price_total);

    	
    })
    //add by yim.hu FUN-BK-0009  配单价格修改 end

    
});
//add by yim.hu FUN-BK-0009  获取url参数 start
function GetQueryString(name) {

	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");

	var r = window.location.search.substr(1).match(reg);

	if (r!=null) return unescape(r[2]); return null;

}
//add by yim.hu FUN-BK-0009  获取url参数 end

